---
title: "Dyadic Representation by Race"
header-includes: \usepackage{float}
date: "2023-08-24"
output:
  html_document:
    df_print: paged
  pdf_document:
    keep_tex: yes
---

```{r setup, include=FALSE}
# Chunk options
knitr::opts_chunk$set(
  echo = FALSE,
  warning = FALSE,
  message = FALSE,
  table.placement = "H"
)

# List of required packages
required_packages <- c(
  "stargazer", "readr", "fixest", "tidyverse", "lfe", "usmap",
  "ggplot2", "gridExtra", "scales", "dotwhisker", "cdlTools", 
  "cowplot", "interflex", "wnominate", "rprojroot", "haven"
)

# Install missing packages
installed <- rownames(installed.packages())
for (pkg in required_packages) {
  if (!(pkg %in% installed)) install.packages(pkg, dependencies = TRUE)
}

# Load packages
lapply(required_packages, library, character.only = TRUE)

# Set root directory to R project folder + subfolder
project_root <- rprojroot::find_root(rprojroot::is_rstudio_project)
setwd(file.path(project_root))

# Define custom not in operator
`%!in%` <- function(x, y) !('%in%'(x, y))
```

# House 

```{r }
# Load main dataset and construct key variables
d <- read_delim("Data/house_vote_level_data_census.csv", 
              delim = ";", escape_double = FALSE, trim_ws = TRUE) %>%
  select(-c(year.y, year.x, year.y.y, year.y.y.y, state_icpsr, state.y, state.y.y)) %>%
  mutate(
    # Create race dummies
    white_r = ifelse(race == 1, 1, 0),
    black_r = ifelse(race == 2, 1, 0),
    latino_r = ifelse(race == 3, 1, 0),
    asian_r = ifelse(race == 4, 1, 0),
    otherrace_r = ifelse(race >= 5, 1, 0),
    native_r = ifelse(race == 5, 1, 0),
    middleeastern_r = ifelse(race == 8, 1, 0),
    otherrace2_r = ifelse(race %in% c(6, 7), 1, 0),
    
    # Demographics and identifiers
    age = year - dob,
    pid7 = ifelse(pid7 > 7, NA, pid7),
    ideo = ifelse(ideo > 7, NA, ideo),
    income = ifelse(income > 4, NA, income),
    female = ifelse(female > 1, NA, female),
    log_d_vap = log(d_vap),
    district_id = paste(state_abbrev, district_code)
  ) %>%
  filter(!is.na(outcome))  # Drop rows without outcome

# Convert district-level columns from character to numeric (handle commas as decimals)
d[c(grep("d_", colnames(d)))] <- sapply(d[c(grep("d_", colnames(d)))], function(x) as.numeric(gsub(",", ".", x)))

# Add congressional control and legislator party indicators
dem_control <- c(2007:2010, 2019:2022)
d$control <- ifelse(d$year %in% dem_control, "Dem", "Rep")
d$dem_leg <- ifelse(d$party_code == "100", 1, 0)  # 1 = Democrat legislator
d$southern_st <- ifelse(d$state_ab %in% .south_region, 1, 0)  # 1 = Southern state
```

```{r}
# Load and merge racial resentment data (pre- and post-2012 redistricting)
pre_rr <- read.csv("Intermediate Data/Racial Resentment House Pre2012.csv")
post_rr <- read.csv("Intermediate Data/Racial Resentment House Post2012.csv")

# Label redistricting period
pre_rr$pre <- 1
post_rr$pre <- 0

# Combine datasets and clean
rr <- bind_rows(pre_rr, post_rr) %>%
  mutate(state = cdlTools::fips(state, to = "Abbreviation")) %>%
  select(-c(X))

rr <- rr[!duplicated(rr[c(1,2,4)]),]

# Mark each row in main dataset as pre- or post-2012
d$pre <- ifelse(d$year < 2012, 1, 0)

# Merge racial resentment data onto main dataset
d <- left_join(d, rr, by = c("state_ab" = "state", "cd", "pre"))
```

# Summary stats

```{r}
mean(subset(d, white_r==1)$outcome)
sd(subset(d, white_r==1)$outcome)
mean(subset(d, white_r==1 & dem_leg==1)$outcome)
sd(subset(d, white_r==1 & dem_leg==1)$outcome)
mean(subset(d, white_r==1 & dem_leg==0)$outcome)
sd(subset(d, white_r==1 & dem_leg==0)$outcome)

mean(subset(d, white_r==1 & pid7 > 4 & dem_leg==0)$outcome)
mean(subset(d, black_r==1 & pid7 > 4 & dem_leg==0)$outcome)
```

## Figure 8 Inputs and SI-O1-2

```{r}
# All Legislators
m1.h <- felm(outcome ~ black_r + latino_r + asian_r + otherrace_r 
             | as.factor(year) + vote | 0 | district_id,
             data = d)
```

```{r}
# Democrat Legislators
m11.h <- felm(outcome ~ black_r + latino_r + asian_r + otherrace_r 
              | as.factor(year) + vote | 0 | district_id,
              data = subset(d, dem_leg == 1))

m12.h <- felm(outcome ~ black_r + latino_r + asian_r + otherrace_r + edu + income + female + age
              | as.factor(year) + vote | 0 | district_id,
              data = subset(d, dem_leg == 1))

m13.h <- felm(outcome ~ black_r + latino_r + asian_r + otherrace_r + ideo
              | as.factor(year) + vote | 0 | district_id,
              data = subset(d, dem_leg == 1))

m14.h <- felm(outcome ~ black_r + latino_r + asian_r + otherrace_r + pid7
              | as.factor(year) + vote | 0 | district_id,
              data = subset(d, dem_leg == 1))

m15.h <- felm(outcome ~ black_r + latino_r + asian_r + otherrace_r + edu + income + female + age + pid7 + ideo +
              log_d_vap + d_p_under35 + d_p_over65 + d_p_college + d_p_hs + d_medinc + d_p_black + d_p_api + d_p_latino
              | as.factor(year) + vote | 0 | district_id,
              data = subset(d, dem_leg == 1))
```

```{r}
# Republican Legislators
m21.h <- felm(outcome ~ black_r + latino_r + asian_r + otherrace_r 
              | as.factor(year) + vote | 0 | district_id,
              data = subset(d, dem_leg == 0))

m22.h <- felm(outcome ~ black_r + latino_r + asian_r + otherrace_r + edu + income + female + age
              | as.factor(year) + vote | 0 | district_id,
              data = subset(d, dem_leg == 0))

m23.h <- felm(outcome ~ black_r + latino_r + asian_r + otherrace_r + ideo
              | as.factor(year) + vote | 0 | district_id,
              data = subset(d, dem_leg == 0))

m24.h <- felm(outcome ~ black_r + latino_r + asian_r + otherrace_r + pid7
              | as.factor(year) + vote | 0 | district_id,
              data = subset(d, dem_leg == 0))

m25.h <- felm(outcome ~ black_r + latino_r + asian_r + otherrace_r + edu + income + female + age + pid7 + ideo +
              log_d_vap + d_p_under35 + d_p_over65 + d_p_college + d_p_hs + d_medinc + d_p_black + d_p_api + d_p_latino
              | as.factor(year) + vote | 0 | district_id,
              data = subset(d, dem_leg == 0))
```

```{r results='asis'}
stargazer(m11.h, m12.h, m13.h, m14.h, m15.h, 
          title = "Table SI-O1",
          add.lines = list(c("DV Mean", 
                             0.624,
                             0.505,0.624,
                             0.505,0.624,
                             0.505)),
          dep.var.labels.include = FALSE , 
          column.sep.width = "1pt", 
          type = "html",
          font.size = "small", 
          header=FALSE, 
          omit.stat = c("f", "ser"), 
          star.char = c("*", "**", "***"),
          star.cutoffs = c(.05, .01, .001),
          out = "Tables/Table SI-O1.doc"
          )
```

```{r results='asis'}
stargazer(m21.h, m22.h, m23.h, m24.h, m25.h,
          title = "Table SI-O2",
          add.lines = list(c("DV Mean", 
                             0.624,
                             0.505,0.624,
                             0.505,0.624,
                             0.505)),
          dep.var.labels.include = FALSE , 
          column.sep.width = "1pt", 
          type = "html",
          font.size = "small", 
          header=FALSE, 
          omit.stat = c("f", "ser"), 
          star.char = c("*", "**", "***"),
          star.cutoffs = c(.05, .01, .001),
          out = "Tables/Table SI-O2.doc"
          )
```

## Figure 10 and SI-G10 Inputs; SI-Q

```{r}
#Race Simple Models with Controls
m1 <- felm(outcome ~ black_r*d_p_black + latino_r*d_p_latino + asian_r*d_p_api + otherrace_r + edu + income + female + age + ideo + pid7 +
               log_d_vap + d_p_under35 + d_p_over65 + d_p_college + d_p_hs + d_medinc + d_p_black + d_p_api + d_p_latino  
               | as.factor(year) + vote | 0 | district_id, data = d)

m2 <- felm(outcome ~ black_r*d_p_black + latino_r*d_p_latino + asian_r*d_p_api + otherrace_r  + edu + income + female + age + ideo + pid7 +
               log_d_vap + d_p_under35 + d_p_over65 + d_p_college + d_p_hs + d_medinc + d_p_black + d_p_api + d_p_latino
               | as.factor(year) + vote | 0 | district_id, data = subset(d, dem_leg == 1))

m3 <- felm(outcome ~ black_r*d_p_black + latino_r*d_p_latino + asian_r*d_p_api + otherrace_r  + edu + income + female + age + ideo + pid7 +
               log_d_vap + d_p_under35 + d_p_over65 + d_p_college + d_p_hs + d_medinc + d_p_black + d_p_api + d_p_latino
               | as.factor(year) + vote | 0 | district_id, data = subset(d, dem_leg == 0))
```

```{r results='asis'}
stargazer(m1,m2,m3,
          title = "Table SI-Q1",
          dep.var.labels.include = FALSE , 
          column.labels = c("All MCs (SI-G10.C1)" , "Democratic MCs", "Republican MCs"),
          column.sep.width = "1pt", 
          type = "html", 
          font.size = "small", 
          header=FALSE, 
          omit.stat = c("f", "ser"), 
          star.char = c("*", "**", "***"),
          star.cutoffs = c(.05, .01, .001),
          out = "Tables/Table SI-Q1.doc"
          )
```

### Figure 10.1

```{r}
# Creating Figure 10.1
beta.hat <- coef(m1)
vcov1 <- vcov(m1)
z01 <- seq(min(d$d_p_black), max(d$d_p_black), length.out = 1000)
dy.dx1 <- beta.hat["black_r"] + beta.hat["black_r:d_p_black"]*z01
se.dy.dx1 <- sqrt(vcov1["black_r", "black_r"] + (z01^2)*vcov1["black_r:d_p_black", "black_r:d_p_black"] + 2*z01*vcov1["black_r", "black_r:d_p_black"])
upr1 <- dy.dx1 + 1.96*se.dy.dx1
lwr1 <- dy.dx1 - 1.96*se.dy.dx1

g1b <- ggplot(data=NULL, aes(x=z01, y=dy.dx1)) +
  labs(x="", y="",
       subtitle = "10.1 Black Respondent | House",
       cex=4) +
  geom_line(aes(z01, dy.dx1),size = 1) +
  geom_line(aes(z01, lwr1), size = 1, linetype = 2, color="blue") +
  geom_line(aes(z01, upr1), size = 1, linetype = 2, color="blue") +
  geom_hline(yintercept=0, size = 1, linetype=1) +
  geom_ribbon(aes(ymin=lwr1, ymax=upr1), alpha=0.3) +
  theme_bw() +
  theme(plot.subtitle = element_text(size = 12)) +
  scale_x_continuous(labels = percent) +
  scale_y_continuous(limits = c(-.17, .15)) +
  theme(plot.subtitle=element_text(size=10))
```

### Figure SI-Q.1

```{r}
beta.hat <- coef(m2)
vcov2 <- vcov(m2)
z02 <- seq(min(d$d_p_black), max(d$d_p_black), length.out = 1000)
dy.dx2 <- beta.hat["black_r"] + beta.hat["black_r:d_p_black"]*z02
se.dy.dx2 <- sqrt(vcov2["black_r", "black_r"] + (z02^2)*vcov2["black_r:d_p_black", "black_r:d_p_black"] + 2*z02*vcov2["black_r", "black_r:d_p_black"])
upr2 <- dy.dx2 + 1.96*se.dy.dx2
lwr2 <- dy.dx2 - 1.96*se.dy.dx2
```

```{r}
beta.hat <- coef(m3)
vcov3 <- vcov(m3)
z03 <- seq(min(d$d_p_black), max(d$d_p_black), length.out = 1000)
dy.dx3 <- beta.hat["black_r"] + beta.hat["black_r:d_p_black"]*z03
se.dy.dx3 <- sqrt(vcov3["black_r", "black_r"] + (z03^2)*vcov3["black_r:d_p_black", "black_r:d_p_black"] + 2*z03*vcov3["black_r", "black_r:d_p_black"])
upr3 <- dy.dx3 + 1.96*se.dy.dx3
lwr3 <- dy.dx3 - 1.96*se.dy.dx3
```

```{r}
g2b <- ggplot(data=NULL, aes(x=z02, y=dy.dx2)) +
  labs(x="", y="",
       subtitle = "Black Respondent | House",
       cex=4) +
  geom_line(aes(z02, dy.dx2),size = 1, color = "blue") +
  geom_line(aes(z02, lwr2), size = 1, linetype = 2, color="blue") +
  geom_line(aes(z02, upr2), size = 1, linetype = 2, color="blue") +
  geom_hline(yintercept=0, size = 1, linetype=3) +
  geom_ribbon(aes(ymin=lwr2, ymax=upr2), alpha=0.3, fill = "blue") +
  geom_line(aes(z03, dy.dx3),size = 1, color = "red") +
  geom_line(aes(z03, lwr3), size = 1, linetype = 2, color="red") +
  geom_line(aes(z03, upr3), size = 1, linetype = 2, color="red") +
  geom_hline(yintercept=0, size = 1, linetype=3) +
  geom_ribbon(aes(ymin=lwr3, ymax=upr3), alpha=0.3, fill = "red") +
  theme_bw() +
  theme(plot.subtitle = element_text(size = 12)) +
  scale_x_continuous(labels = percent) +
  scale_y_continuous(limits = c(-.2, .1)) +
  theme(plot.subtitle=element_text(size=10))
```

### Figure 10.2

```{r}
beta.hat <- coef(m1)
vcov1 <- vcov(m1)
z01.l <- seq(min(d$d_p_latino), max(d$d_p_latino), length.out = 1000)
dy.dx1.l <- beta.hat["latino_r"] + beta.hat["latino_r:d_p_latino"]*z01.l
se.dy.dx1.l <- sqrt(vcov1["latino_r", "latino_r"] + (z01.l^2)*vcov1["latino_r:d_p_latino", "latino_r:d_p_latino"] + 2*z01.l*vcov1["latino_r", "latino_r:d_p_latino"])
upr1.l <- dy.dx1.l + 1.96*se.dy.dx1.l
lwr1.l <- dy.dx1.l - 1.96*se.dy.dx1.l

g1l <- ggplot(data=NULL, aes(x=z01.l, y=dy.dx1.l)) +
  labs(x="", y="",
       subtitle = "10.2 Latino Respondent | House",
       cex=4) +
  geom_line(aes(z01.l, dy.dx1.l),size = 1) +
  geom_line(aes(z01.l, lwr1.l), size = 1, linetype = 2, color="blue") +
  geom_line(aes(z01.l, upr1.l), size = 1, linetype = 2, color="blue") +
  geom_hline(yintercept=0, size = 1, linetype=1) +
  geom_ribbon(aes(ymin=lwr1.l, ymax=upr1.l), alpha=0.3) +
  theme_bw() +
  theme(plot.subtitle = element_text(size = 12)) +
  scale_x_continuous(labels = percent) +
  scale_y_continuous(limits = c(-.17,.15)) +
  theme(plot.subtitle=element_text(size=10))
  
```

```{r}
beta.hat <- coef(m2)
vcov2.l <- vcov(m2)
z02.l <- seq(min(d$d_p_latino), max(d$d_p_latino), length.out = 1000)
dy.dx2.l <- beta.hat["latino_r"] + beta.hat["latino_r:d_p_latino"]*z02.l
se.dy.dx2.l <- sqrt(vcov2.l["latino_r", "latino_r"] + (z02.l^2)*vcov2.l["latino_r:d_p_latino", "latino_r:d_p_latino"] + 2*z02.l*vcov2.l["latino_r", "latino_r:d_p_latino"])
upr2.l <- dy.dx2.l + 1.96*se.dy.dx2.l
lwr2.l <- dy.dx2.l - 1.96*se.dy.dx2.l
```

```{r}
beta.hat <- coef(m3)
vcov3.l <- vcov(m3)
z03.l <- seq(min(d$d_p_latino), max(d$d_p_latino), length.out = 1000)
dy.dx3.l <- beta.hat["latino_r"] + beta.hat["latino_r:d_p_latino"]*z03.l
se.dy.dx3.l <- sqrt(vcov3.l["latino_r", "latino_r"] + (z03.l^2)*vcov3.l["latino_r:d_p_latino", "latino_r:d_p_latino"] + 2*z03.l*vcov3.l["latino_r", "latino_r:d_p_latino"])
upr3.l <- dy.dx3.l + 1.96*se.dy.dx3.l
lwr3.l <- dy.dx3.l - 1.96*se.dy.dx3.l
```

### Figure SI-Q.2

```{r}
g2l <- ggplot(data=NULL, aes(x=z02.l, y=dy.dx2.l)) +
  labs(x="", y="",
       subtitle = "Latino Respondent | House",
       cex=4) +
  geom_line(aes(z02.l, dy.dx2.l),size = 1, color = "blue") +
  geom_line(aes(z02.l, lwr2.l), size = 1, linetype = 2, color="blue") +
  geom_line(aes(z02.l, upr2.l), size = 1, linetype = 2, color="blue") +
  geom_hline(yintercept=0, size = 1, linetype=3) +
  geom_ribbon(aes(ymin=lwr2.l, ymax=upr2.l), alpha=0.3, fill = "blue") +
  geom_line(aes(z03.l, dy.dx3.l),size = 1, color = "red") +
  geom_line(aes(z03.l, lwr3.l), size = 1, linetype = 2, color="red") +
  geom_line(aes(z03.l, upr3.l), size = 1, linetype = 2, color="red") +
  geom_hline(yintercept=0, size = 1, linetype=3) +
  geom_ribbon(aes(ymin=lwr3.l, ymax=upr3.l), alpha=0.3, fill = "red") +
  theme_bw() +
  theme(plot.subtitle = element_text(size = 12)) +
  scale_x_continuous(labels = percent) +
  scale_y_continuous(limits = c(-.2, .1)) +
  theme(plot.subtitle=element_text(size=10))
```

```{r}
legdata <- data.frame(c("Democrat", "Republican", "Democrat", "Republican"), c(1,2,3,4), c(2,1,6,7))
colnames(legdata) <- c("Party", "X", "Y")

leg <- ggplot(data=legdata, aes(x=X, y=Y, color=Party, fill=Party)) +
  geom_line(size=4) +
  scale_color_manual(values = c("blue", "red")) +
  theme(legend.direction = "horizontal")

g_legend <- function(a.gplot){
  tmp <- ggplot_gtable(ggplot_build(a.gplot))
  leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
  legend <- tmp$grobs[[leg]]
  return(legend)
}

leg <- g_legend(leg)
```

## Figure 11 House

```{r}
#Race Simple Models with Controls
m1 <- felm(outcome ~ black_r*white_racial_resentment + latino_r + asian_r + otherrace_r  + edu + income + female + age + ideo + pid7 +
               log_d_vap + d_p_under35 + d_p_over65 + d_p_college + d_p_hs + d_medinc + d_p_black + d_p_api + d_p_latino 
               | as.factor(year) + vote | 0 | district_id, data = d)

m2 <- felm(outcome ~ black_r*white_racial_resentment + latino_r + asian_r + otherrace_r  + edu + income + female + age + ideo + pid7 +
               log_d_vap + d_p_under35 + d_p_over65 + d_p_college + d_p_hs + d_medinc + d_p_black + d_p_api + d_p_latino 
               | as.factor(year) + vote | 0 | district_id, data = subset(d, dem_leg==1))

m3 <- felm(outcome ~ black_r*white_racial_resentment + latino_r + asian_r + otherrace_r + edu + income + female + age + ideo + pid7 +
               log_d_vap + d_p_under35 + d_p_over65 + d_p_college + d_p_hs + d_medinc + d_p_black + d_p_api + d_p_latino 
               | as.factor(year) + vote | 0 | district_id, data = subset(d, dem_leg==0))
```

```{r results='asis'}
stargazer(m1,m2,m3,
          title = "Table G11",
          dep.var.labels.include = FALSE , 
          column.sep.width = "1pt", 
          type = "html",
          font.size = "small", 
          header=FALSE, 
          omit.stat = c("f", "ser"), 
          star.char = c("*", "**", "***"),
          star.cutoffs = c(.05, .01, .001),
          out = "Tables/Table SI-G11.doc"
          )
```

### Figure 11.1

```{r }
beta.hat <- coef(m1)
vcov1 <- vcov(m1)
z0 <- seq(min(d$white_racial_resentment, na.rm = TRUE), max(d$white_racial_resentment, na.rm = TRUE), length.out = 1000)
dy.dx <- beta.hat["black_r"] + beta.hat["black_r:white_racial_resentment"]*z0
se.dy.dx <- sqrt(vcov1["black_r", "black_r"] + (z0^2)*vcov1["black_r:white_racial_resentment", "black_r:white_racial_resentment"] + 2*z0*vcov1["black_r", "black_r:white_racial_resentment"])
upr <- dy.dx + 1.96*se.dy.dx
lwr <- dy.dx - 1.96*se.dy.dx
g1 <- ggplot(data=NULL, aes(x=z0, y=dy.dx)) +
  labs(x="District White Racial Resentment (Scale: 1-5)", y="Marginal Effects",
       subtitle=paste("11.1 All Representatives"),
       cex=4) +
  geom_line(aes(z0, dy.dx),size = 1) +
  geom_line(aes(z0, lwr), size = 1, linetype = 2, color="blue") +
  geom_line(aes(z0, upr), size = 1, linetype = 2, color="blue") +
  geom_hline(yintercept=0, size = 1, linetype=3) +
  geom_ribbon(aes(ymin=lwr, ymax=upr), alpha=0.3) +
  theme_bw(base_size = 12) +
  theme(axis.text.x = element_text(size=8),
           axis.text.y = element_text(size=8),
        axis.title=element_text(size=9)) +
  scale_y_continuous(limits = c(-.37, .3))

```

```{r}
s_rr <- d %>%
  group_by(state_ab, cd) %>%
  summarise(rr = mean(white_racial_resentment),
            black_pop = mean(d_p_black))
```

```{r fig.width=3.1, fig.height=2.7}
xhist  <- 
  axis_canvas(g1, axis = "x") + 
  geom_histogram(data = s_rr,
                 aes(x = rr),
                 color = 'black',
                 fill= 'lightgray') 

g1 <- g1 %>%
  insert_xaxis_grob(xhist , grid::unit(.3, "in"), position = "top") %>%
  ggdraw()

g1
```

### Figure 11.3

```{r }
beta.hat <- coef(m2)
vcov1 <- vcov(m2)
z0 <- seq(min(d$white_racial_resentment, na.rm = TRUE), max(d$white_racial_resentment, na.rm = TRUE), length.out = 1000)
dy.dx <- beta.hat["black_r"] + beta.hat["black_r:white_racial_resentment"]*z0
se.dy.dx <- sqrt(vcov1["black_r", "black_r"] + (z0^2)*vcov1["black_r:white_racial_resentment", "black_r:white_racial_resentment"] + 2*z0*vcov1["black_r", "black_r:white_racial_resentment"])
upr <- dy.dx + 1.96*se.dy.dx
lwr <- dy.dx - 1.96*se.dy.dx

g2 <- ggplot(data=NULL, aes(x=z0, y=dy.dx)) +
  labs(x="District White Racial Resentment (Scale: 1-5)", y="Marginal Effects",
       subtitle=paste("11.3 Democratic Representatives"),
       cex=4) +
  geom_line(aes(z0, dy.dx),size = 1) +
  geom_line(aes(z0, lwr), size = 1, linetype = 2, color="blue") +
  geom_line(aes(z0, upr), size = 1, linetype = 2, color="blue") +
  geom_hline(yintercept=0, size = 1, linetype=3) +
  geom_ribbon(aes(ymin=lwr, ymax=upr), alpha=0.3) +
  theme_bw() +
  theme_bw(base_size = 12) +
  theme(axis.text.x = element_text(size=8),
           axis.text.y = element_text(size=8),
        axis.title=element_text(size=9)) +
  scale_y_continuous(limits = c(-.37, .3))
```

```{r}
s_rr <- d %>%
  subset(dem_leg ==1) %>%
    group_by(state_ab, cd) %>%
  summarise(rr = mean(white_racial_resentment),
            black_pop = mean(d_p_black))
```

```{r fig.width=3.1, fig.height=2.7}
xhist  <- 
  axis_canvas(g2, axis = "x") + 
  geom_histogram(data = s_rr,
                 aes(x = rr),
                 color = 'black',
                 fill= 'lightgray') 

g2 <- g2 %>%
  insert_xaxis_grob(xhist , grid::unit(.3, "in"), position = "top") %>%
  ggdraw()

g2
```

### Figure 11.5

```{r }
beta.hat <- coef(m3)
vcov1 <- vcov(m3)
z0 <- seq(min(d$white_racial_resentment, na.rm = TRUE), max(d$white_racial_resentment, na.rm = TRUE), length.out = 1000)
dy.dx <- beta.hat["black_r"] + beta.hat["black_r:white_racial_resentment"]*z0
se.dy.dx <- sqrt(vcov1["black_r", "black_r"] + (z0^2)*vcov1["black_r:white_racial_resentment", "black_r:white_racial_resentment"] + 2*z0*vcov1["black_r", "black_r:white_racial_resentment"])
upr <- dy.dx + 1.96*se.dy.dx
lwr <- dy.dx - 1.96*se.dy.dx
g3 <- ggplot(data=NULL, aes(x=z0, y=dy.dx)) +
  labs(x="District White Racial Resentment (Scale: 1-5)", y="Marginal Effects",
       subtitle=paste("11.5 Republican Representatives"),
       cex=4) +
  geom_line(aes(z0, dy.dx),size = 1) +
  geom_line(aes(z0, lwr), size = 1, linetype = 2, color="blue") +
  geom_line(aes(z0, upr), size = 1, linetype = 2, color="blue") +
  geom_hline(yintercept=0, size = 1, linetype=3) +
  geom_ribbon(aes(ymin=lwr, ymax=upr), alpha=0.3) +
  theme_bw() +
  theme_bw(base_size = 12) +
  theme(axis.text.x = element_text(size=8),
           axis.text.y = element_text(size=8),
        axis.title=element_text(size=9)) +
  scale_y_continuous(limits = c(-.37, .3))
```

```{r}
s_rr <- d %>%
  subset(dem_leg ==0) %>%
    group_by(state_ab, cd) %>%
  summarise(rr = mean(white_racial_resentment),
            black_pop = mean(d_p_black))
```

```{r fig.width=3.1, fig.height=2.7}
xhist  <- 
  axis_canvas(g3, axis = "x") + 
  geom_histogram(data = s_rr,
                 aes(x = rr),
                 color = 'black',
                 fill= 'lightgray') 

g3 <- g3 %>%
  insert_xaxis_grob(xhist , grid::unit(.3, "in"), position = "top") %>%
  ggdraw()

g3
```

## Figure 10 and SI-G10 Inputs; SI-Q

```{r}
#Race Simple Models with Controls
m1 <- felm(outcome ~ black_r*d_p_black + latino_r*d_p_latino + asian_r*d_p_api + otherrace_r + edu + income + female + age + ideo + pid7 +
               log_d_vap + d_p_under35 + d_p_over65 + d_p_college + d_p_hs + d_medinc + d_p_black + d_p_api + d_p_latino  
               | as.factor(year) + vote | 0 | district_id, data = d)

m2 <- felm(outcome ~ black_r*d_p_black + latino_r*d_p_latino + asian_r*d_p_api + otherrace_r  + edu + income + female + age + ideo + pid7 +
               log_d_vap + d_p_under35 + d_p_over65 + d_p_college + d_p_hs + d_medinc + d_p_black + d_p_api + d_p_latino
               | as.factor(year) + vote | 0 | district_id, data = d)

m3 <- felm(outcome ~ black_r*d_p_black + latino_r*d_p_latino + asian_r*d_p_api + otherrace_r  + edu + income + female + age + ideo + pid7 +
               log_d_vap + d_p_under35 + d_p_over65 + d_p_college + d_p_hs + d_medinc + d_p_black + d_p_api + d_p_latino
               | as.factor(year) + vote | 0 | district_id, data = d)
```

```{r results='asis'}
stargazer(m1,m2,m3,
          title = "Table SI-Q1",
          dep.var.labels.include = FALSE , 
          column.labels = c("All MCs (SI-G10.C1)" , "Democratic MCs", "Republican MCs"),
          column.sep.width = "1pt", 
          type = "html", 
          font.size = "small", 
          header=FALSE, 
          omit.stat = c("f", "ser"), 
          star.char = c("*", "**", "***"),
          star.cutoffs = c(.05, .01, .001),
          out = "Tables/Table SI-Q1.doc"
          )
```

## SI-M

```{r}
# Democrat Legislators
m11.h <- felm(outcome ~ black_r + latino_r + asian_r + otherrace_r 
              | as.factor(year) + vote | 0 | district_id,
              data = subset(d, dem_leg == 1),
              weights = subset(d, dem_leg == 1)$weight)

m15.h <- felm(outcome ~ black_r + latino_r + asian_r + otherrace_r + edu + income + female + age + pid7 + ideo +
              log_d_vap + d_p_under35 + d_p_over65 + d_p_college + d_p_hs + d_medinc + d_p_black + d_p_api + d_p_latino
              | as.factor(year) + vote | 0 | district_id,
              data = subset(d, dem_leg == 1),
              weights = subset(d, dem_leg == 1)$weight)
```

```{r}
# Republican Legislators
m21.h <- felm(outcome ~ black_r + latino_r + asian_r + otherrace_r 
              | as.factor(year) + vote | 0 | district_id,
              data = subset(d, dem_leg == 0),
              weights = subset(d, dem_leg == 0)$weight)

m25.h <- felm(outcome ~ black_r + latino_r + asian_r + otherrace_r + edu + income + female + age + pid7 + ideo +
              log_d_vap + d_p_under35 + d_p_over65 + d_p_college + d_p_hs + d_medinc + d_p_black + d_p_api + d_p_latino
              | as.factor(year) + vote | 0 | district_id,
              data = subset(d, dem_leg == 0),
              weights = subset(d, dem_leg == 0)$weight)
```

```{r results='asis'}
stargazer(m11.h, m15.h, m21.h, m25.h,
          title = "Table SI-M1",
          add.lines = list(c("DV Mean", 
                             0.624,
                             0.505,0.624,
                             0.505,0.624,
                             0.505)),
          dep.var.labels.include = FALSE , 
          column.sep.width = "1pt", 
          type = "html",
          font.size = "small", 
          header=FALSE, 
          omit.stat = c("f", "ser"), 
          star.char = c("*", "**", "***"),
          star.cutoffs = c(.05, .01, .001),
          out = "Tables/Table SI-M1.doc"
          )
```

```{r}
#Race Simple Models with Controls
m0 <- felm(outcome ~ black_r*d_p_black + latino_r*d_p_latino  + asian_r*d_p_api + otherrace_r  + edu + income + female + age + ideo + pid7 +
               log_d_vap + d_p_under35 + d_p_over65 + d_p_college + d_p_hs + d_medinc + d_p_black + d_p_api + d_p_latino 
               | as.factor(year) + vote | 0 | district_id, data = d, weights = d$weight)

m1 <- felm(outcome ~ black_r*white_racial_resentment + latino_r + asian_r + otherrace_r  + edu + income + female + age + ideo + pid7 +
               log_d_vap + d_p_under35 + d_p_over65 + d_p_college + d_p_hs + d_medinc + d_p_black + d_p_api + d_p_latino 
               | as.factor(year) + vote | 0 | district_id, data = d, weights = d$weight)

m2 <- felm(outcome ~ black_r*white_racial_resentment + latino_r + asian_r + otherrace_r  + edu + income + female + age + ideo + pid7 +
               log_d_vap + d_p_under35 + d_p_over65 + d_p_college + d_p_hs + d_medinc + d_p_black + d_p_api + d_p_latino 
               | as.factor(year) + vote | 0 | district_id, data = subset(d, dem_leg==1), weights = subset(d, dem_leg==1)$weight)

m3 <- felm(outcome ~ black_r*white_racial_resentment + latino_r + asian_r + otherrace_r + edu + income + female + age + ideo + pid7 +
               log_d_vap + d_p_under35 + d_p_over65 + d_p_college + d_p_hs + d_medinc + d_p_black + d_p_api + d_p_latino 
               | as.factor(year) + vote | 0 | district_id, data = subset(d, dem_leg==0), weights = subset(d, dem_leg==0)$weight)
```

```{r results='asis'}
stargazer(m0, m1,m2,m3,
          title = "Table SI-M2",
          dep.var.labels.include = FALSE , 
          column.sep.width = "1pt", 
          type = "html",
          font.size = "small", 
          header=FALSE, 
          omit.stat = c("f", "ser"), 
          star.char = c("*", "**", "***"),
          star.cutoffs = c(.05, .01, .001),
          out = "Tables/Table SI-M3.doc"
          )
```


## SI-P House

```{r message=FALSE, include=FALSE}

g1_int <- interflex(Y = "outcome", D = "black_r", X = "d_p_black", data = as.data.frame(d), estimator = "binning", cutoffs = c(.1,.2,.3,.4,.5,.6),  vcov.type = "cluster", cl = "district_id", na.rm = T, main = "Marginal Effects of Being Black By Share\nof District Black on Dyadic Advantage\n(v. Whites) in the House", Ylabel = "Black-White Gap", Dlabel = "Black Respondent", Xlabel="Share of District Black",  theme.bw = TRUE, ylab = "Marginal Effect: Black Respondent", cex.main = .6, cex.lab = .7, cex.axis = .6, Z = c("latino_r", "asian_r" , "otherrace_r", "edu" , "income" , "female" , "age" , "ideo",  "pid7" , "log_d_vap" , "d_p_under35" , "d_p_over65" , "d_p_college" , "d_p_hs" , "d_medinc" , "d_p_black" , "d_p_api" , "d_p_latino" ), FE = c("year", "vote"), weights = "weight")


g2_int <- interflex(Y = "outcome", D = "latino_r", X = "d_p_latino", data = as.data.frame(d),estimator = "binning", cutoffs = c(.1,.2,.3,.4,.5,.6,.7), na.rm = T, vcov.type = "cluster", cl = "district_id",  main = "Marginal Effects of Being Latino By Share\nof District Latino on Dyadic Advantage\n(v. Whites) in the House", Ylabel = "Latino-White Gap", Dlabel = "Latino Respondent", Xlabel="Share of District Latino",   theme.bw = TRUE, ylab = "Marginal Effect: Latino Respondent", cex.main = .6, cex.lab = .7, cex.axis = .6, Z = c("black_r", "asian_r" , "otherrace_r", "edu" , "income" , "female" , "age" , "ideo",  "pid7" , "log_d_vap" , "d_p_under35" , "d_p_over65" , "d_p_college" , "d_p_hs" , "d_medinc" , "d_p_black" , "d_p_api" , "d_p_latino" ), FE = c("year", "vote"), weights = "weight")



gc()

```

```{r fig.width= 3.1, fig.height= 4}

g1_int
g2_int
```

## SI-S House

```{r}
#Race Simple Models with Controls

m2 <- felm(outcome ~ black_r*d_p_black + latino_r*d_p_latino + asian_r*d_p_api + otherrace_r  + edu + income + female + age + ideo + pid7 +
               log_d_vap + d_p_under35 + d_p_over65 + d_p_college + d_p_hs + d_medinc + d_p_black + d_p_api + d_p_latino
               | as.factor(year) + vote | 0 | district_id, data = subset(d, southern_st==1))

m3 <- felm(outcome ~ black_r*d_p_black + latino_r*d_p_latino + asian_r*d_p_api + otherrace_r  + edu + income + female + age + ideo + pid7 +
               log_d_vap + d_p_under35 + d_p_over65 + d_p_college + d_p_hs + d_medinc + d_p_black + d_p_api + d_p_latino
               | as.factor(year) + vote | 0 | district_id, data = subset(d, southern_st==0))
```

```{r results='asis'}
stargazer(m2,m3,
          title = "SI-S",
          dep.var.labels.include = FALSE , 
          column.labels = c("Southern MCs", "Non-Southern MCs"),
          column.sep.width = "1pt", 
          type = "html", 
          font.size = "small", 
          header=FALSE, 
          omit.stat = c("f", "ser"), 
          star.char = c("*", "**", "***"),
          star.cutoffs = c(.05, .01, .001)
          )
```

### Figure SI-S.1

```{r}
beta.hat <- coef(m3)
vcov2.sou <- vcov(m3)
z02.sou <- seq(min(d$d_p_black), max(d$d_p_black), length.out = 1000)
dy.dx2.sou <- beta.hat["black_r"] + beta.hat["black_r:d_p_black"]*z02.sou
se.dy.dx2.sou <- sqrt(vcov2.sou["black_r", "black_r"] + (z02.sou^2)*vcov2.sou["black_r:d_p_black", "black_r:d_p_black"] + 2*z02.sou*vcov2.sou["black_r", "black_r:d_p_black"])
upr2.sou <- dy.dx2.sou + 1.96*se.dy.dx2.sou
lwr2.sou <- dy.dx2.sou - 1.96*se.dy.dx2.sou
```

```{r}
beta.hat <- coef(m2)
vcov3.sou <- vcov(m2)
z03.sou <- seq(min(d$d_p_black), max(d$d_p_black), length.out = 1000)
dy.dx3.sou <- beta.hat["black_r"] + beta.hat["black_r:d_p_black"]*z03.sou
se.dy.dx3.sou <- sqrt(vcov3.sou["black_r", "black_r"] + (z03.sou^2)*vcov3.sou["black_r:d_p_black", "black_r:d_p_black"] + 2*z03.sou*vcov3.sou["black_r", "black_r:d_p_black"])
upr3.sou <- dy.dx3.sou + 1.96*se.dy.dx3.sou
lwr3.sou <- dy.dx3.sou - 1.96*se.dy.dx3.sou
```

```{r}
g2b.sou <- ggplot(data=NULL, aes(x=z02.sou, y=dy.dx2.sou)) +
  labs(x="", y="",
       subtitle = "Black Respondent | House",
       cex=4) +
  geom_line(aes(z02.sou, dy.dx2.sou),size = 1, color = "blue") +
  geom_line(aes(z02.sou, lwr2.sou), size = 1, linetype = 2, color="blue") +
  geom_line(aes(z02.sou, upr2.sou), size = 1, linetype = 2, color="blue") +
  geom_hline(yintercept=0, size = 1, linetype=3) +
  geom_ribbon(aes(ymin=lwr2.sou, ymax=upr2.sou), alpha=0.3, fill = "blue") +
  geom_line(aes(z03.sou, dy.dx3.sou),size = 1, color = "red") +
  geom_line(aes(z03.sou, lwr3.sou), size = 1, linetype = 2, color="red") +
  geom_line(aes(z03.sou, upr3.sou), size = 1, linetype = 2, color="red") +
  geom_hline(yintercept=0, size = 1, linetype=3) +
  geom_ribbon(aes(ymin=lwr3.sou, ymax=upr3.sou), alpha=0.3, fill = "red") +
  theme_bw() +
  theme(plot.subtitle = element_text(size = 12)) +
  scale_x_continuous(labels = percent) +
  scale_y_continuous(limits = c(-.37, .3)) +
  theme(plot.subtitle=element_text(size=10))
```

### Figure SI-S.2

```{r}
beta.hat <- coef(m3)
vcov2.l.sou <- vcov(m3)
z02.l.sou <- seq(min(d$d_p_latino), max(d$d_p_latino), length.out = 1000)
dy.dx2.l.sou <- beta.hat["latino_r"] + beta.hat["latino_r:d_p_latino"]*z02.l.sou
se.dy.dx2.l.sou <- sqrt(vcov2.l.sou["latino_r", "latino_r"] + (z02.l.sou^2)*vcov2.l.sou["latino_r:d_p_latino", "latino_r:d_p_latino"] + 2*z02.l.sou*vcov2.l.sou["latino_r", "latino_r:d_p_latino"])
upr2.l.sou <- dy.dx2.l.sou + 1.96*se.dy.dx2.l.sou
lwr2.l.sou <- dy.dx2.l.sou - 1.96*se.dy.dx2.l.sou
```

```{r}
beta.hat <- coef(m2)
vcov3.l.sou <- vcov(m2)
z03.l.sou <- seq(min(d$d_p_latino), max(d$d_p_latino), length.out = 1000)
dy.dx3.l.sou <- beta.hat["latino_r"] + beta.hat["latino_r:d_p_latino"]*z03.l.sou
se.dy.dx3.l.sou <- sqrt(vcov3.l.sou["latino_r", "latino_r"] + (z03.l.sou^2)*vcov3.l.sou["latino_r:d_p_latino", "latino_r:d_p_latino"] + 2*z03.l.sou*vcov3.l.sou["latino_r", "latino_r:d_p_latino"])
upr3.l.sou <- dy.dx3.l.sou + 1.96*se.dy.dx3.l.sou
lwr3.l.sou <- dy.dx3.l.sou - 1.96*se.dy.dx3.l.sou
```

```{r}
g2l.sou <- ggplot(data=NULL, aes(x=z02.l.sou, y=dy.dx2.l.sou)) +
  labs(x="", y="",
       subtitle = "Latino Respondent | House",
       cex=4) +
  geom_line(aes(z02.l.sou, dy.dx2.l.sou),size = 1, color = "blue") +
  geom_line(aes(z02.l.sou, lwr2.l.sou), size = 1, linetype = 2, color="blue") +
  geom_line(aes(z02.l.sou, upr2.l.sou), size = 1, linetype = 2, color="blue") +
  geom_hline(yintercept=0, size = 1, linetype=3) +
  geom_ribbon(aes(ymin=lwr2.l.sou, ymax=upr2.l.sou), alpha=0.3, fill = "blue") +
  geom_line(aes(z03.l.sou, dy.dx3.l.sou),size = 1, color = "red") +
  geom_line(aes(z03.l.sou, lwr3.l.sou), size = 1, linetype = 2, color="red") +
  geom_line(aes(z03.l.sou, upr3.l.sou), size = 1, linetype = 2, color="red") +
  geom_hline(yintercept=0, size = 1, linetype=3) +
  geom_ribbon(aes(ymin=lwr3.l.sou, ymax=upr3.l.sou), alpha=0.3, fill = "red") +
  theme_bw() +
  theme(plot.subtitle = element_text(size = 12)) +
  scale_x_continuous(labels = percent) +
  scale_y_continuous(limits = c(-.37,.3))+
  theme(plot.subtitle=element_text(size=10))
```

### Figure SI-S2

```{r}
d$pre2012 <- ifelse(d$year <=2012, 1, 0)
  
d_agg <- d %>%
  subset(race <= 2) %>%
  group_by(race, pre2012, cd, state_ab) %>%
  summarise(outcome = mean(outcome),
            black_pop = mean(d_p_black)) %>%
  mutate(race = car::recode(race, "'1'='White';'2'='Black'")) %>%
  pivot_wider(id_cols = c(pre2012, state_ab, cd), names_from = race, values_from = c(outcome, black_pop)) %>%
  mutate(values = outcome_Black-outcome_White) %>%
  select(-c(black_pop_White)) %>%
  rename(black_pop=black_pop_Black,
         state=state_ab) 

d_agg$southern_st <- ifelse(d_agg$state %in% .south_region, 1, 0)
```

```{r}
ggplot(d_agg, aes(x = black_pop, y = values)) +
  geom_point(aes(color = as.factor(southern_st)), check_overlap = TRUE, size = 3, position = "jitter") +
  geom_smooth(method = "loess", aes(x = black_pop, y = values, group = as.factor(southern_st), color = as.factor(southern_st)), alpha = .8) +
  labs(x = "Proportion of District Population Black", y = "Black-White Dyadic Representation Gap", color = "Southern State") +
  theme_bw() 
```
## SI-V House

```{r}
#Race Simple Models with Controls

m2 <- felm(outcome ~ black_r*white_racial_resentment + latino_r + asian_r + otherrace_r  + edu + income + female + age + ideo + pid7 +
               log_d_vap + d_p_under35 + d_p_over65 + d_p_college + d_p_hs + d_medinc + d_p_black + d_p_api + d_p_latino 
               | as.factor(year) + vote | 0 | district_id, data = subset(d, southern_st==1))

m3 <- felm(outcome ~ black_r*white_racial_resentment + latino_r + asian_r + otherrace_r + edu + income + female + age + ideo + pid7 +
               log_d_vap + d_p_under35 + d_p_over65 + d_p_college + d_p_hs + d_medinc + d_p_black + d_p_api + d_p_latino 
               | as.factor(year) + vote | 0 | district_id, data = subset(d, southern_st==0))
```

```{r results='asis'}
stargazer(m2,m3,
          title = "SI-V.1 and SI-V.2",
          dep.var.labels.include = FALSE , 
          column.sep.width = "1pt", 
          column.labels = c("Southern State", "Non-Southern State"),
          type = "html",
          font.size = "small", 
          header=FALSE, 
          omit.stat = c("f", "ser"), 
          star.char = c("*", "**", "***"),
          star.cutoffs = c(.05, .01, .001)
          )
```

### SI-V.1

```{r }
beta.hat <- coef(m2)
vcov1 <- vcov(m2)
z0 <- seq(min(d$white_racial_resentment, na.rm = TRUE), max(d$white_racial_resentment, na.rm = TRUE), length.out = 1000)
dy.dx <- beta.hat["black_r"] + beta.hat["black_r:white_racial_resentment"]*z0
se.dy.dx <- sqrt(vcov1["black_r", "black_r"] + (z0^2)*vcov1["black_r:white_racial_resentment", "black_r:white_racial_resentment"] + 2*z0*vcov1["black_r", "black_r:white_racial_resentment"])
upr <- dy.dx + 1.96*se.dy.dx
lwr <- dy.dx - 1.96*se.dy.dx

g2 <- ggplot(data=NULL, aes(x=z0, y=dy.dx)) +
  labs(x="District White Racial Resentment (Scale: 1-5)", y="Marginal Effects",
       subtitle=paste("Southern Representatives"),
       cex=4) +
  geom_line(aes(z0, dy.dx),size = 1) +
  geom_line(aes(z0, lwr), size = 1, linetype = 2, color="blue") +
  geom_line(aes(z0, upr), size = 1, linetype = 2, color="blue") +
  geom_hline(yintercept=0, size = 1, linetype=3) +
  geom_ribbon(aes(ymin=lwr, ymax=upr), alpha=0.3) +
  theme_bw() +
  theme_bw(base_size = 12) +
  theme(axis.text.x = element_text(size=8),
           axis.text.y = element_text(size=8),
        axis.title=element_text(size=9)) +
  scale_y_continuous(limits = c(-.37, .3))
```

```{r}
s_rr <- d %>%
  subset(dem_leg ==1) %>%
    group_by(state_ab, cd) %>%
  summarise(rr = mean(white_racial_resentment),
            black_pop = mean(d_p_black))
```

```{r fig.width=3.1, fig.height=2.7}
xhist  <- 
  axis_canvas(g2, axis = "x") + 
  geom_histogram(data = s_rr,
                 aes(x = rr),
                 color = 'black',
                 fill= 'lightgray') 

g2 <- g2 %>%
  insert_xaxis_grob(xhist , grid::unit(.3, "in"), position = "top") %>%
  ggdraw()

g2
```

### SI-V.2

```{r }
beta.hat <- coef(m3)
vcov1 <- vcov(m3)
z0 <- seq(min(d$white_racial_resentment, na.rm = TRUE), max(d$white_racial_resentment, na.rm = TRUE), length.out = 1000)
dy.dx <- beta.hat["black_r"] + beta.hat["black_r:white_racial_resentment"]*z0
se.dy.dx <- sqrt(vcov1["black_r", "black_r"] + (z0^2)*vcov1["black_r:white_racial_resentment", "black_r:white_racial_resentment"] + 2*z0*vcov1["black_r", "black_r:white_racial_resentment"])
upr <- dy.dx + 1.96*se.dy.dx
lwr <- dy.dx - 1.96*se.dy.dx
g3 <- ggplot(data=NULL, aes(x=z0, y=dy.dx)) +
  labs(x="District White Racial Resentment (Scale: 1-5)", y="Marginal Effects",
       subtitle=paste("Non-Southern Representatives"),
       cex=4) +
  geom_line(aes(z0, dy.dx),size = 1) +
  geom_line(aes(z0, lwr), size = 1, linetype = 2, color="blue") +
  geom_line(aes(z0, upr), size = 1, linetype = 2, color="blue") +
  geom_hline(yintercept=0, size = 1, linetype=3) +
  geom_ribbon(aes(ymin=lwr, ymax=upr), alpha=0.3) +
  theme_bw() +
  theme_bw(base_size = 12) +
  theme(axis.text.x = element_text(size=8),
           axis.text.y = element_text(size=8),
        axis.title=element_text(size=9)) +
  scale_y_continuous(limits = c(-.37, .3))
```

```{r}
s_rr <- d %>%
  subset(dem_leg ==0) %>%
    group_by(state_ab, cd) %>%
  summarise(rr = mean(white_racial_resentment),
            black_pop = mean(d_p_black))
```

```{r fig.width=3.1, fig.height=2.7}
xhist  <- 
  axis_canvas(g3, axis = "x") + 
  geom_histogram(data = s_rr,
                 aes(x = rr),
                 color = 'black',
                 fill= 'lightgray') 

g3 <- g3 %>%
  insert_xaxis_grob(xhist , grid::unit(.3, "in"), position = "top") %>%
  ggdraw()

g3
```

# Senate

```{r }
# Define roll call votes for judicial/nomination votes to exclude
nominations <- c("2017_rcv8_r", "2017_rcv2_r", "2009_rcv7_r", "2018_rcv4_r", 
                 "2019_rcv3_r", "2022_rcv7_r", "2020_rcv3_r", "2018_rcv1_r", 
                 "2016_rcv1_r")

# Load Senate-level vote data and construct variables
d <- read_delim("Data/senate_vote_level_data_census.csv", 
              delim = ";", escape_double = FALSE, trim_ws = TRUE) %>%
  select(-c(year.y, year.x, year.y.y, year.y.y.y, state_icpsr, state.y, state.y.y)) %>%
  mutate(
    # Race dummy variables
    white_r = ifelse(race == 1, 1, 0),
    black_r = ifelse(race == 2, 1, 0),
    latino_r = ifelse(race == 3, 1, 0),
    asian_r = ifelse(race == 4, 1, 0),
    otherrace_r = ifelse(race >= 5, 1, 0),
    native_r = ifelse(race == 5, 1, 0),
    middleeastern_r = ifelse(race == 8, 1, 0),
    otherrace2_r = ifelse(race %in% c(6, 7), 1, 0),

    # Demographics and unique ID
    age = year - dob,
    pid7 = ifelse(pid7 > 7, NA, pid7),
    ideo = ifelse(ideo > 7, NA, ideo),
    income = ifelse(income > 4, NA, income),
    female = ifelse(female > 1, NA, female),
    log_s_vap = log(s_vap),
    year_vote = paste(year, resp_vote_ID, sep = "_")
  ) %>%
  filter(!is.na(outcome) & year_vote %!in% nominations)  # Remove NAs and nominations

# Convert district-level vars from character to numeric
d[c(grep("s_", colnames(d)))] <- sapply(d[c(grep("s_", colnames(d)))], function(x) as.numeric(gsub(",", ".", x)))
d$dem.presvote.lastup <- sapply(d$dem.presvote.lastup, function(x) as.numeric(gsub(",", ".", x)))

# Tag chamber control and legislator party
dem_control <- c(2007:2012, 2021:2022)
d$control <- ifelse(d$year %in% dem_control, "Dem", "Rep")
d$dem_leg <- ifelse(d$party_code == "100", 1, 0)
d$southern_st <- ifelse(d$state_ab %in% .south_region, 1, 0)
```

```{r}
# Load and merge state-level racial resentment scores
rr <- read.csv("Intermediate Data/Racial Resentment Senate.csv") %>%
  mutate(state = cdlTools::fips(state, to = "Abbreviation")) %>%
  subset(state != "DC") %>%
  select(-c(X))

d <- left_join(d, rr, by = c("state_ab" = "state"))
```


```{r}
# Load state-level ideology estimates from AIP dataset
ideo <- read_dta("Intermediate Data/aip_states_ideology_v2022a.dta") %>%
  select(state, abb, mrp_ideology, presidential_year)

# Join using closest prior presidential year
d <- left_join(d, ideo, join_by("state_ab" == "abb", closest(year <= presidential_year)))
```

## Summary Stats

```{r}
# Means and SDs for White respondents overall and by legislator party
weighted.mean(subset(d, white_r == 1)$outcome, subset(d, white_r == 1)$weight)
sd(subset(d, white_r == 1)$outcome)
weighted.mean(subset(d, white_r == 1 & dem_leg == 1)$outcome, subset(d, white_r == 1 & dem_leg == 1)$weight)
sd(subset(d, white_r == 1 & dem_leg == 1)$outcome)
weighted.mean(subset(d, white_r == 1 & dem_leg == 0)$outcome, subset(d, white_r == 1 & dem_leg == 0)$weight)
sd(subset(d, white_r == 1 & dem_leg == 0)$outcome)

# Outcomes by race and party among right-leaning respondents
mean(subset(d, white_r == 1 & pid7 > 4 & dem_leg == 0)$outcome)
mean(subset(d, black_r == 1 & pid7 > 4 & dem_leg == 0)$outcome)
```

## Figure 8 Inputs

```{r}
# Race models without controls — all, Dem, and GOP legislators
m1.s <- felm(outcome ~ black_r + latino_r + asian_r + otherrace_r 
             | as.factor(year) + vote | 0 | state.y, 
             data = d,
             weights = d$weight)

m11.s <- felm(outcome ~ black_r + latino_r + asian_r + otherrace_r 
              | as.factor(year) + vote | 0 | state.y, 
              data = subset(d, dem_leg == 1),
              weights = subset(d, dem_leg == 1)$weight)

m21.s <- felm(outcome ~ black_r + latino_r + asian_r + otherrace_r 
              | as.factor(year) + vote | 0 | state.y, 
              data = subset(d, dem_leg == 0),
              weights = subset(d, dem_leg == 0)$weight)
```


```{r}
#Models with demographic controls
m12.s <- felm(outcome ~ black_r + latino_r + asian_r + otherrace_r + edu + income + female + age
              | as.factor(year) + vote | 0 | state.y, 
              data = subset(d, dem_leg == 1),
              weights = subset(d, dem_leg == 1)$weight)

m22.s <- felm(outcome ~ black_r + latino_r + asian_r + otherrace_r + edu + income + female + age
              | as.factor(year) + vote | 0 | state.y, 
              data = subset(d, dem_leg == 0),
              weights = subset(d, dem_leg == 0)$weight)
```

```{r}
# Models with ideology
m13.s <- felm(outcome ~ black_r + latino_r + asian_r + otherrace_r + ideo
              | as.factor(year) + vote | 0 | state.y, 
              data = subset(d, dem_leg == 1),
              weights = subset(d, dem_leg == 1)$weight)

m23.s <- felm(outcome ~ black_r + latino_r + asian_r + otherrace_r + ideo
              | as.factor(year) + vote | 0 | state.y, 
              data = subset(d, dem_leg == 0),
              weights = subset(d, dem_leg == 0)$weight)
```

```{r}
# Models with partisanship
m14.s <- felm(outcome ~ black_r + latino_r + asian_r + otherrace_r + pid7 
              | as.factor(year) + vote | 0 | state.y, 
              data = subset(d, dem_leg == 1),
              weights = subset(d, dem_leg == 1)$weight)

m24.s <- felm(outcome ~ black_r + latino_r + asian_r + otherrace_r + pid7 
              | as.factor(year) + vote | 0 | state.y, 
              data = subset(d, dem_leg == 0),
              weights = subset(d, dem_leg == 0)$weight)
```


```{r}
# Fully saturated models with district-level controls
m15.s <- felm(outcome ~ black_r + latino_r + asian_r + otherrace_r + edu + income + female + age + pid7 + ideo +
              log_s_vap + s_p_under35 + s_p_over65 + s_p_college + s_p_hs + s_medinc + s_p_black + s_p_api + s_p_latino
              | as.factor(year) + vote | 0 | state.y, 
              data = subset(d, dem_leg == 1),
              weights = subset(d, dem_leg == 1)$weight)

m25.s <- felm(outcome ~ black_r + latino_r + asian_r + otherrace_r + edu + income + female + age + pid7 + ideo +
              log_s_vap + s_p_under35 + s_p_over65 + s_p_college + s_p_hs + s_medinc + s_p_black + s_p_api + s_p_latino
              | as.factor(year) + vote | 0 | state.y, 
              data = subset(d, dem_leg == 0),
              weights = subset(d, dem_leg == 0)$weight)
```

```{r results='asis'}
stargazer(m1.h, m1.s,
          title = "Table SI-N",
          add.lines = list(c("DV Mean", 
                             0.624,
                             0.505,0.624,
                             0.505,0.624,
                             0.505)),
          dep.var.labels.include = FALSE , 
          column.sep.width = "1pt", 
          type = "html",
          font.size = "small", 
          header=FALSE, 
          omit.stat = c("f", "ser"), 
          star.char = c("*", "**", "***"),
          star.cutoffs = c(.05, .01, .001),
          out = "Tables/Table SI-N.doc"
          )
```

```{r results='asis'}
stargazer(m11.s, m12.s, m13.s, m14.s, m15.s, 
          title = "Table SI-O3",
          add.lines = list(c("DV Mean", 
                             0.624,
                             0.505,0.624,
                             0.505,0.624,
                             0.505)),
          dep.var.labels.include = FALSE , 
          column.sep.width = "1pt", 
          type = "html",
          font.size = "small", 
          header=FALSE, 
          omit.stat = c("f", "ser"), 
          star.char = c("*", "**", "***"),
          star.cutoffs = c(.05, .01, .001),
          out = "Tables/Table SI-O3.doc"
          )
```


```{r results='asis'}
stargazer(m21.s, m22.s, m23.s, m24.s, m25.s, 
          title = "Table SI-O4",
          dep.var.labels.include = FALSE , 
          column.sep.width = "1pt", 
          type = "html",
          font.size = "small", 
          header=FALSE, 
          omit.stat = c("f", "ser"), 
          star.char = c("*", "**", "***"),
          star.cutoffs = c(.05, .01, .001),
          out = "Tables/Table SI-O4.doc"
          )
```

# Figure 8

```{r fig.height=8.5, fig.width=6.5}

m1df <- broom::tidy(m11.h) %>% 
  filter(term %in% c("black_r", "latino_r", "asian_r")) %>% 
  mutate(model = "No Covariates")

m5df <- broom::tidy(m15.h) %>% 
  filter(term %in% c("black_r", "latino_r", "asian_r")) %>% 
  mutate(model = "All Covariates")

models <- rbind(m1df, m5df) 

 
g1 <- dwplot(models, ci = 0.95,
       vline = geom_vline(
           xintercept = 0,
           colour = "grey60",
           linetype = 2
       ),  dot_args = list(aes(shape = model))) %>% # plot line at zero _behind_coefs
    relabel_predictors(
        c(  black_r = "Black",
            latino_r = "Latino",
            asian_r = "Asian"
        )) + # plot line at zero _behind_ coefs
    theme_bw(base_size = 11) + xlab("") + ylab("") +
    labs(subtitle = "8.1 Democratic House Representative") +
    theme(
        plot.title = element_text(face = "bold"),
        legend.position = c(0.007, 0.01),
        legend.justification = c(0, 0),
        legend.background = element_rect(colour = "grey80"),
        legend.title.align = .5
    ) +
    scale_colour_grey(
        start = .1,
        end = .7
    ) +
    scale_shape_discrete(
        name = "Model",
    ) +
    guides(
        shape = guide_legend("", nrow=1,byrow=TRUE), 
        colour = guide_legend("", nrow=1,byrow=TRUE)) +
        theme(legend.direction="horizontal") +
  scale_x_continuous(limits = c(-0.21, 0.18)) 


g_legend<-function(a.gplot){
  tmp <- ggplot_gtable(ggplot_build(a.gplot))
  leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
  legend <- tmp$grobs[[leg]]
  return(legend)}

mylegend<-g_legend(g1)

g1 <- g1 + theme(legend.position="none") + labs(x="")


m1df <- broom::tidy(m11.s) %>% 
  filter(term %in% c("black_r", "latino_r", "asian_r")) %>% 
  mutate(model = "No Covariates")

m5df <- broom::tidy(m15.s) %>% 
  filter(term %in% c("black_r", "latino_r", "asian_r")) %>% 
  mutate(model = "All Covariates")

models <- rbind(m1df, m5df) 

 
g2 <- dwplot(models, ci = 0.95,
       vline = geom_vline(
           xintercept = 0,
           colour = "grey60",
           linetype = 2
       ),  dot_args = list(aes(shape = model))) %>% # plot line at zero _behind_coefs
    relabel_predictors(
        c(  black_r = "Black",
            latino_r = "Latino",
            asian_r = "Asian"
        )) + # plot line at zero _behind_ coefs
    theme_bw(base_size = 11) + xlab("") + ylab("") +
    labs(subtitle = "8.3 Democratic Senator") +
    theme(
        plot.title = element_text(face = "bold"),
        legend.position = c(0.007, 0.01),
        legend.justification = c(0, 0),
        legend.background = element_rect(colour = "grey80"),
        legend.title.align = .5
    ) +
    scale_colour_grey(
        start = .1,
        end = .7,
        breaks = c("Model 1", "Model 2", "Model 3"),
        name = "Model",
        labels = c("TWFE", "TWFE & Controls", "TWFE, Controls, & Linear Trends")
    ) +
    scale_shape_discrete(
          breaks = c("Model 1", "Model 2", "Model 3"),
        name = "Model",
        labels = c("TWFE", "TWFE & Controls", "TWFE, Controls, & Linear Trends")
    ) +
    guides(
        shape = guide_legend("Model"), 
        colour = guide_legend("Model")) +
        theme(legend.position = c(0.55, 0.01)
    ) + theme(legend.position="none") +
  scale_x_continuous(limits = c(-0.21, 0.18))

g2 <- g2 + theme(legend.position="none") + labs(x="")



m1df <- broom::tidy(m21.h) %>% 
  filter(term %in% c("black_r", "latino_r", "asian_r")) %>% 
  mutate(model = "No Covariates")
  
m5df <- broom::tidy(m25.h) %>% 
  filter(term %in% c("black_r", "latino_r", "asian_r")) %>% 
  mutate(model = "All Covariates")

models <- rbind(m1df, m5df) 

 
g3 <- dwplot(models, ci = 0.95,
       vline = geom_vline(
           xintercept = 0,
           colour = "grey60",
           linetype = 2
       ),  dot_args = list(aes(shape = model))) %>% # plot line at zero _behind_coefs
    relabel_predictors(
        c(  black_r = "Black",
            latino_r = "Latino",
            asian_r = "Asian"
        )) + # plot line at zero _behind_ coefs
    theme_bw(base_size = 11) + xlab("") + ylab("") +
    labs(subtitle = "8.2 Republican House Representative") +
    theme(
        plot.title = element_text(face = "bold"),
        legend.position = c(0.007, 0.01),
        legend.justification = c(0, 0),
        legend.background = element_rect(colour = "grey80"),
        legend.title.align = .5
    ) +
    scale_colour_grey(
        start = .1,
        end = .7
    ) +
    scale_shape_discrete(
        name = "Model",
    ) +
    guides(
        shape = guide_legend(""), 
        colour = guide_legend("")) +
        theme(legend.direction="horizontal") +
  scale_x_continuous(limits = c(-0.21, 0.18))

g3 <- g3 + theme(legend.position="none") + labs(x="")


m1df <- broom::tidy(m21.s) %>% 
  filter(term %in% c("black_r", "latino_r", "asian_r")) %>% 
  mutate(model = "No Covariates")

m5df <- broom::tidy(m25.s) %>% 
  filter(term %in% c("black_r", "latino_r", "asian_r")) %>% 
  mutate(model = "All Covariates")

models <- rbind(m1df,  m5df) 

 
g4 <- dwplot(models, ci = 0.95,
       vline = geom_vline(
           xintercept = 0,
           colour = "grey60",
           linetype = 2
       ),  dot_args = list(aes(shape = model))) %>% # plot line at zero _behind_coefs
    relabel_predictors(
        c(  black_r = "Black",
            latino_r = "Latino",
            asian_r = "Asian"
        )) + # plot line at zero _behind_ coefs
    theme_bw(base_size = 11) + xlab("Coefficient Estimate") + ylab("") +
    labs(subtitle = "8.4 Republican Senator") +
    theme(
        plot.title = element_text(face = "bold"),
        legend.position = c(0.007, 0.01),
        legend.justification = c(0, 0),
        legend.background = element_rect(colour = "grey80"),
        legend.title.align = .5
    ) +
    scale_colour_grey(
        start = .1,
        end = .7
    ) +
    scale_shape_discrete(
        name = "Model",
    ) +
    guides(
        shape = guide_legend(""), 
        colour = guide_legend("")) +
        theme(legend.direction="horizontal") +
  scale_x_continuous(limits = c(-0.21, 0.18))

g4 <- g4 + theme(legend.position="none") 



lay = rbind(
            c(2,2,2,2,2,2),
            c(2,2,2,2,2,2),
            c(2,2,2,2,2,2),
            c(2,2,2,2,2,2),
            c(3,3,3,3,3,3),
            c(3,3,3,3,3,3),
            c(3,3,3,3,3,3),
            c(3,3,3,3,3,3),
            c(4,4,4,4,4,4),
            c(4,4,4,4,4,4),
            c(4,4,4,4,4,4),
            c(4,4,4,4,4,4),
            c(5,5,5,5,5,5),
            c(5,5,5,5,5,5),
            c(5,5,5,5,5,5),
            c(5,5,5,5,5,5),
            c(NA,NA,1,1,1,NA),
            c(NA,NA,1,1,1,NA))

p3 <- grid.arrange(mylegend,g1,g3,g2,g4, layout_matrix=lay)
```

## Figure 9

```{r }
d <- d %>%
  unite("state_year", c(state.x, year), remove = F) %>%
  mutate(rep_leg = as.numeric(dplyr::recode(dem_leg, "1" = "0", "0" = "1")))

m1 <- felm(outcome ~ black_r*rep_leg + latino_r*rep_leg + asian_r*rep_leg + otherrace_r*rep_leg 
               | state_year + vote | 0 | state.y, data = d, weights = d$weight)


m2 <- felm(outcome ~ black_r*rep_leg + latino_r*rep_leg + asian_r*rep_leg + otherrace_r*rep_leg + pid7*rep_leg 
               | state_year + vote | 0 | state.y, data = d, weights = d$weight)
```

```{r results='asis'}
stargazer(m1, m2, 
          title = "Table SI-G9",
          dep.var.labels.include = FALSE , 
          column.sep.width = "1pt", 
          type = "html",
          font.size = "small", 
          header=FALSE, 
          omit.stat = c("f", "ser"), 
          star.char = c("*", "**", "***"),
          star.cutoffs = c(.05, .01, .001),
          out = "Tables/Table SI-G9.doc"
          )
```

```{r}
m1df <- broom::tidy(m1) %>% 
  mutate(model = "No PID Covariate") %>%
  subset(!grepl("other",term) & !is.nan(estimate))

m2df <- broom::tidy(m2) %>% 
  mutate(model = "PID Covariate") %>%
  subset(!grepl("other",term) & !is.nan(estimate))

models1 <- rbind(m1df, m2df) %>%
  relabel_predictors(black_r = "Black Respondent*\nDemocratic Senator",
                     latino_r = "Latino Respondent*\nDemocratic Senator",
                     asian_r = "Asian Respondent*\nDemocratic Senator",
                     rep_leg = "Republican Senator",
                     "black_r:rep_leg" = "Black Respondent*\nRepublican Senator",
                     "rep_leg:latino_r" = "Latino Respondent*\nRepublican Senator",
                     "rep_leg:asian_r" = "Asian Respondent*\nRepublican Senator",
                     pid7 = "Respondent's Party ID",
                     "rep_leg:pid7" = "Respondent's Party ID*\nRepublican Senator")


dwplot(models1, ci = 0.95,
       vline = geom_vline(
           xintercept = 0,
           colour = "grey60",
           linetype = 2
       ), dot_args = list(aes(shape = model))) +
    theme_bw(base_size = 11) + xlab("") + ylab("") +
    theme(
        plot.title = element_text(face = "bold"),
        legend.position = "bottom",
        legend.background = element_rect(colour = "grey80"),
    ) +
    scale_x_continuous(limits = c(-0.4,0.2)) +
    guides(
        shape = guide_legend(""), 
        colour = guide_legend("")) +
        theme(legend.direction="horizontal") + scale_color_grey(start = .2, end = .6) +
  labs(x = "Coefficient Estimate")
```


## Figure 10 & SI-Q Senate

```{r}
#Race Simple Models with Controls
m1 <- felm(outcome ~ black_r*s_p_black + latino_r*s_p_latino + asian_r*s_p_api + otherrace_r + edu + income + female + age + ideo + pid7 +
               log_s_vap + s_p_under35 + s_p_over65 + s_p_college + s_p_hs + s_medinc 
               | as.factor(year) + vote | 0 | state.y, data = d, weights = d$weight)

m2 <- felm(outcome ~ black_r*s_p_black + latino_r*s_p_latino + asian_r*s_p_api + otherrace_r + edu + income + female + age + ideo + pid7 +
               log_s_vap + s_p_under35 + s_p_over65 + s_p_college + s_p_hs + s_medinc 
               | as.factor(year) + vote | 0 | state.y, data = subset(d, dem_leg == 1), weights = subset(d, dem_leg == 1)$weight)

m3 <- felm(outcome ~ black_r*s_p_black + latino_r*s_p_latino + asian_r*s_p_api + otherrace_r + edu + income + female + age + ideo + pid7 +
               log_s_vap + s_p_under35 + s_p_over65 + s_p_college + s_p_hs + s_medinc 
               | as.factor(year) + vote | 0 | state.y, data = subset(d, dem_leg == 0), weights = subset(d, dem_leg == 0)$weight)
```

```{r results='asis'}
stargazer(m1,m2,m3,
          title = "Table SI-Q2",
          dep.var.labels.include = FALSE , 
          column.labels = c("All MCs (Table SI-G10 (2))" , "Democratic MCs", "Republican MCs"),
          column.sep.width = "1pt", 
          type = "html", 
          font.size = "small", 
          header=FALSE, 
          omit.stat = c("f", "ser"), 
          star.char = c("*", "**", "***"),
          star.cutoffs = c(.05, .01, .001),
          out = "Tables/Table SI-Q2"
          )
```

### Figure 10.3

```{r}
beta.hat <- coef(m1)
vcov1 <- vcov(m1)
z01.s <- seq(min(d$s_p_black), max(d$s_p_black), length.out = 1000)
dy.dx1.s <- beta.hat["black_r"] + beta.hat["black_r:s_p_black"]*z01.s
se.dy.dx1.s <- sqrt(vcov1["black_r", "black_r"] + (z01.s^2)*vcov1["black_r:s_p_black", "black_r:s_p_black"] + 2*z01.s*vcov1["black_r", "black_r:s_p_black"])
upr1.s <- dy.dx1.s + 1.96*se.dy.dx1.s
lwr1.s <- dy.dx1.s - 1.96*se.dy.dx1.s

g1.sb <- ggplot(data=NULL, aes(x=z01.s, y=dy.dx1.s)) +
  labs(x="", y="",
       subtitle = "10.3 Black Respondent | Senate",
       cex=4) +
  geom_line(aes(z01.s, dy.dx1.s),size = 1) +
  geom_line(aes(z01.s, lwr1.s), size = 1, linetype = 2, color="blue") +
  geom_line(aes(z01.s, upr1.s), size = 1, linetype = 2, color="blue") +
  geom_hline(yintercept=0, size = 1, linetype=1) +
  geom_ribbon(aes(ymin=lwr1.s, ymax=upr1.s), alpha=0.3) +
  theme_bw() +
  theme(plot.subtitle = element_text(size = 12)) +
  scale_x_continuous(labels = percent) +
  scale_y_continuous(limits = c(-.25, .2)) +
  theme(plot.subtitle=element_text(size=10))
```

### Figure SI-Q.3

```{r}
beta.hat <- coef(m2)
vcov2 <- vcov(m2)
z02.s <- seq(min(d$s_p_black), max(d$s_p_black), length.out = 1000)
dy.dx2.s <- beta.hat["black_r"] + beta.hat["black_r:s_p_black"]*z02.s
se.dy.dx2.s <- sqrt(vcov2["black_r", "black_r"] + (z02.s^2)*vcov2["black_r:s_p_black", "black_r:s_p_black"] + 2*z02.s*vcov2["black_r", "black_r:s_p_black"])
upr2.s <- dy.dx2.s + 1.96*se.dy.dx2.s
lwr2.s <- dy.dx2.s - 1.96*se.dy.dx2.s
```

```{r}
beta.hat <- coef(m3)
vcov3 <- vcov(m3)
z03.s <- seq(min(d$s_p_black), max(d$s_p_black), length.out = 1000)
dy.dx3.s <- beta.hat["black_r"] + beta.hat["black_r:s_p_black"]*z03.s
se.dy.dx3.s <- sqrt(vcov3["black_r", "black_r"] + (z03.s^2)*vcov3["black_r:s_p_black", "black_r:s_p_black"] + 2*z03.s*vcov3["black_r", "black_r:s_p_black"])
upr3.s <- dy.dx3.s + 1.96*se.dy.dx3.s
lwr3.s <- dy.dx3.s - 1.96*se.dy.dx3.s
```

```{r}
g2.sb <- ggplot(data=NULL, aes(x=z02.s, y=dy.dx2.s)) +
  labs(x="", y="",
       subtitle = "Black Respondent | Senate",
       cex=4) +
  geom_line(aes(z02.s, dy.dx2.s),size = 1, color = "blue") +
  geom_line(aes(z02.s, lwr2.s), size = 1, linetype = 2, color="blue") +
  geom_line(aes(z02.s, upr2.s), size = 1, linetype = 2, color="blue") +
  geom_hline(yintercept=0, size = 1, linetype=3) +
  geom_ribbon(aes(ymin=lwr2.s, ymax=upr2.s), alpha=0.3, fill = "blue") +
  geom_line(aes(z03.s, dy.dx3.s),size = 1, color = "red") +
  geom_line(aes(z03.s, lwr3.s), size = 1, linetype = 2, color="red") +
  geom_line(aes(z03.s, upr3.s), size = 1, linetype = 2, color="red") +
  geom_hline(yintercept=0, size = 1, linetype=3) +
  geom_ribbon(aes(ymin=lwr3.s, ymax=upr3.s), alpha=0.3, fill = "red") +
  theme_bw() +
  theme(plot.subtitle = element_text(size = 12)) +
  scale_x_continuous(labels = percent) +
  scale_y_continuous(limits = c(-.2, .1)) +
  theme(plot.subtitle=element_text(size=10))
```

### Figure10.4

```{r}
beta.hat <- coef(m1)
vcov1 <- vcov(m1)
z01.s.l <- seq(min(d$s_p_latino), max(d$s_p_latino), length.out = 1000)
dy.dx1.s.l <- beta.hat["latino_r"] + beta.hat["latino_r:s_p_latino"]*z01.s.l
se.dy.dx1.s.l <- sqrt(vcov1["latino_r", "latino_r"] + (z01.s.l^2)*vcov1["latino_r:s_p_latino", "latino_r:s_p_latino"] + 2*z01.s.l*vcov1["latino_r", "latino_r:s_p_latino"])
upr1.s.l <- dy.dx1.s.l + 1.96*se.dy.dx1.s.l
lwr1.s.l <- dy.dx1.s.l - 1.96*se.dy.dx1.s.l

g1.sl <- ggplot(data=NULL, aes(x=z01.s.l, y=dy.dx1.s.l)) +
  labs(x="", y="",
       subtitle = "10.4 Latino Respondent | Senate",
       cex=4) +
  geom_line(aes(z01.s.l, dy.dx1.s.l),size = 1) +
  geom_line(aes(z01.s.l, lwr1.s.l), size = 1, linetype = 2, color="blue") +
  geom_line(aes(z01.s.l, upr1.s.l), size = 1, linetype = 2, color="blue") +
  geom_hline(yintercept=0, size = 1, linetype=1) +
  geom_ribbon(aes(ymin=lwr1.s.l, ymax=upr1.s.l), alpha=0.3) +
  theme_bw() +
  theme(plot.subtitle = element_text(size = 12)) +
  scale_x_continuous(labels = percent) +
  scale_y_continuous(limits = c(-.25, .2)) +
  theme(plot.subtitle=element_text(size=10))
  
```

### Figure SI-Q.4

```{r}
beta.hat <- coef(m2)
vcov2.l <- vcov(m2)
z02.s.l <- seq(min(d$s_p_latino), max(d$s_p_latino), length.out = 1000)
dy.dx2.s.l <- beta.hat["latino_r"] + beta.hat["latino_r:s_p_latino"]*z02.s.l
se.dy.dx2.s.l <- sqrt(vcov2.l["latino_r", "latino_r"] + (z02.s.l^2)*vcov2.l["latino_r:s_p_latino", "latino_r:s_p_latino"] + 2*z02.s.l*vcov2.l["latino_r", "latino_r:s_p_latino"])
upr2.s.l <- dy.dx2.s.l + 1.96*se.dy.dx2.s.l
lwr2.s.l <- dy.dx2.s.l - 1.96*se.dy.dx2.s.l
```

```{r}
beta.hat <- coef(m3)
vcov3.l <- vcov(m3)
z03.s.l <- seq(min(d$s_p_latino), max(d$s_p_latino), length.out = 1000)
dy.dx3.s.l <- beta.hat["latino_r"] + beta.hat["latino_r:s_p_latino"]*z03.s.l
se.dy.dx3.s.l <- sqrt(vcov3.l["latino_r", "latino_r"] + (z03.s.l^2)*vcov3.l["latino_r:s_p_latino", "latino_r:s_p_latino"] + 2*z03.s.l*vcov3.l["latino_r", "latino_r:s_p_latino"])
upr3.s.l <- dy.dx3.s.l + 1.96*se.dy.dx3.s.l
lwr3.s.l <- dy.dx3.s.l - 1.96*se.dy.dx3.s.l
```

```{r}
g2.sl <- ggplot(data=NULL, aes(x=z02.s.l, y=dy.dx2.s.l)) +
  labs(x="", y="",
       subtitle = "Latino Respondent | Senate",
       cex=4) +
  geom_line(aes(z02.s.l, dy.dx2.s.l),size = 1, color = "blue") +
  geom_line(aes(z02.s.l, lwr2.s.l), size = 1, linetype = 2, color="blue") +
  geom_line(aes(z02.s.l, upr2.s.l), size = 1, linetype = 2, color="blue") +
  geom_hline(yintercept=0, size = 1, linetype=3) +
  geom_ribbon(aes(ymin=lwr2.s.l, ymax=upr2.s.l), alpha=0.3, fill = "blue") +
  geom_line(aes(z03.s.l, dy.dx3.s.l),size = 1, color = "red") +
  geom_line(aes(z03.s.l, lwr3.s.l), size = 1, linetype = 2, color="red") +
  geom_line(aes(z03.s.l, upr3.s.l), size = 1, linetype = 2, color="red") +
  geom_hline(yintercept=0, size = 1, linetype=3) +
  geom_ribbon(aes(ymin=lwr3.s.l, ymax=upr3.s.l), alpha=0.3, fill = "red") +
  theme_bw() +
  theme(plot.subtitle = element_text(size = 12)) +
  scale_x_continuous(labels = percent) +
  scale_y_continuous(limits = c(-.2, .1)) +
  theme(plot.subtitle=element_text(size=10))
```

### Figure SI-Q 

```{r}

legdata <- data.frame(c("Democrat", "Republican", "Democrat", "Republican"), c(1,2,3,4), c(2,1,6,7))
colnames(legdata) <- c("Party", "X", "Y")

leg <- ggplot(data=legdata, aes(x=X, y=Y, color=Party, fill=Party)) +
  geom_line(size=4) +
  scale_color_manual(values = c("blue", "red")) +
  theme(legend.direction = "horizontal")

g_legend <- function(a.gplot){
  tmp <- ggplot_gtable(ggplot_build(a.gplot))
  leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
  legend <- tmp$grobs[[leg]]
  return(legend)
}

leg <- g_legend(leg)
```

```{r, fig.height=6, fig.width=6}

lay = rbind(c(1,1,1,1,2,2,2,2),
            c(1,1,1,1,2,2,2,2),
            c(1,1,1,1,2,2,2,2),
            c(1,1,1,1,2,2,2,2),
            c(1,1,1,1,2,2,2,2),
            c(1,1,1,1,2,2,2,2),
            c(1,1,1,1,2,2,2,2),
            c(3,3,3,3,4,4,4,4),
            c(3,3,3,3,4,4,4,4),
            c(3,3,3,3,4,4,4,4),
            c(3,3,3,3,4,4,4,4),
            c(3,3,3,3,4,4,4,4),
            c(3,3,3,3,4,4,4,4),
            c(3,3,3,3,4,4,4,4),
            c(NA,NA,5,5,5,5,NA,NA))

grid.arrange( g2b, g2l, g2.sb, g2.sl, leg, layout_matrix=lay, 
             bottom = "Percent of the District / State Population Black / Latino",
             left = "Marginal Effects")
```

```{r, fig.height=6, fig.width=6}

lay = rbind(c(1,1,1,1,2,2,2,2),
            c(1,1,1,1,2,2,2,2),
            c(1,1,1,1,2,2,2,2),
            c(1,1,1,1,2,2,2,2),
            c(1,1,1,1,2,2,2,2),
            c(1,1,1,1,2,2,2,2),
            c(1,1,1,1,2,2,2,2),
            c(3,3,3,3,4,4,4,4),
            c(3,3,3,3,4,4,4,4),
            c(3,3,3,3,4,4,4,4),
            c(3,3,3,3,4,4,4,4),
            c(3,3,3,3,4,4,4,4),
            c(3,3,3,3,4,4,4,4),
            c(3,3,3,3,4,4,4,4))

grid.arrange( g1b, g1l, g1.sb, g1.sl,layout_matrix=lay, 
             bottom = "Percent of the District / State Population Black / Latino",
             left = "Marginal Effects")
```

## Figure 11, SI-G Tables Senate

```{r}
s_rr <- d %>%
  group_by(state_ab) %>%
  summarise(rr = mean(white_racial_resentment),
            black_pop = mean(s_p_black),
            latino_pop = mean(s_p_latino))
```

```{r}
m1 <- felm(outcome ~ black_r*white_racial_resentment + latino_r + asian_r + otherrace_r + edu + income + female + age + ideo + pid7 +
               log_s_vap + s_p_under35 + s_p_over65 + s_p_college + s_p_hs + s_medinc + s_p_black + s_p_api + s_p_latino
               | as.factor(year) + vote | 0 | state.y, data = d, weights = d$weight)

m2 <- felm(outcome ~ black_r*white_racial_resentment + latino_r + asian_r + otherrace_r + edu + income + female + age + ideo + pid7 +
               log_s_vap + s_p_under35 + s_p_over65 + s_p_college + s_p_hs + s_medinc + s_p_black + s_p_api + s_p_latino
               | as.factor(year) + vote | 0 | state.y, data = subset(d, dem_leg==1), weights = subset(d, dem_leg==1)$weight)

m3 <- felm(outcome ~ black_r*white_racial_resentment + latino_r + asian_r + otherrace_r + edu + income + female + age + ideo + pid7 +
               log_s_vap + s_p_under35 + s_p_over65 + s_p_college + s_p_hs + s_medinc + s_p_black + s_p_api + s_p_latino
               | as.factor(year) + vote | 0 | state.y, data = subset(d, dem_leg==0), weights = subset(d, dem_leg==0)$weight)
```

### Table SI-G12

```{r results='asis'}
stargazer(m1,m2,m3,
          title = "Table SI-G12",
          dep.var.labels.include = FALSE , 
          column.sep.width = "1pt", 
          type = "html",
          font.size = "small", 
          header=FALSE, 
          omit.stat = c("f", "ser"), 
          star.char = c("*", "**", "***"),
          star.cutoffs = c(.05, .01, .001),
          out = "Tables/Table SI-G12.doc"
          )
```

### Figure 11.2

```{r }
beta.hat <- coef(m1)
vcov1 <- vcov(m1)
z0 <- seq(min(d$white_racial_resentment, na.rm = TRUE), max(d$white_racial_resentment, na.rm = TRUE), length.out = 1000)
dy.dx <- beta.hat["black_r"] + beta.hat["black_r:white_racial_resentment"]*z0
se.dy.dx <- sqrt(vcov1["black_r", "black_r"] + (z0^2)*vcov1["black_r:white_racial_resentment", "black_r:white_racial_resentment"] + 2*z0*vcov1["black_r", "black_r:white_racial_resentment"])
upr <- dy.dx + 1.96*se.dy.dx
lwr <- dy.dx - 1.96*se.dy.dx
g1 <- ggplot(data=NULL, aes(x=z0, y=dy.dx)) +
  labs(x="State White Racial Resentment (Scale: 1-5)", y="Marginal Effects",
       subtitle=paste("11.2 All Senators"),
       cex=4) +
  geom_line(aes(z0, dy.dx),size = 1) +
  geom_line(aes(z0, lwr), size = 1, linetype = 2, color="blue") +
  geom_line(aes(z0, upr), size = 1, linetype = 2, color="blue") +
  geom_hline(yintercept=0, size = 1, linetype=3) +
  geom_ribbon(aes(ymin=lwr, ymax=upr), alpha=0.3) +
  theme_bw(base_size = 12) +
  theme(axis.text.x = element_text(size=8),
           axis.text.y = element_text(size=8),
        axis.title=element_text(size=9)) +
  scale_y_continuous(limits = c(-.37, .3))

```

```{r}
s_rr <- d %>%
  group_by(state_ab) %>%
  summarise(rr = mean(white_racial_resentment),
            black_pop = mean(s_p_black))
```

```{r fig.width=3.1, fig.height=2.7}
xhist  <- 
  axis_canvas(g1, axis = "x") + 
  geom_histogram(data = s_rr,
                 aes(x = rr),
                 color = 'black',
                 fill= 'lightgray') 

g1 <- g1 %>%
  insert_xaxis_grob(xhist , grid::unit(.3, "in"), position = "top") %>%
  ggdraw()

g1
```

### Figure 11.4

```{r }
beta.hat <- coef(m2)
vcov1 <- vcov(m2)
z0 <- seq(min(d$white_racial_resentment, na.rm = TRUE), max(d$white_racial_resentment, na.rm = TRUE), length.out = 1000)
dy.dx <- beta.hat["black_r"] + beta.hat["black_r:white_racial_resentment"]*z0
se.dy.dx <- sqrt(vcov1["black_r", "black_r"] + (z0^2)*vcov1["black_r:white_racial_resentment", "black_r:white_racial_resentment"] + 2*z0*vcov1["black_r", "black_r:white_racial_resentment"])
upr <- dy.dx + 1.96*se.dy.dx
lwr <- dy.dx - 1.96*se.dy.dx

g2 <- ggplot(data=NULL, aes(x=z0, y=dy.dx)) +
  labs(x="State White Racial Resentment (Scale: 1-5)", y="Marginal Effects",
       subtitle=paste("11.4 Democratic Senators"),
       cex=4) +
  geom_line(aes(z0, dy.dx),size = 1) +
  geom_line(aes(z0, lwr), size = 1, linetype = 2, color="blue") +
  geom_line(aes(z0, upr), size = 1, linetype = 2, color="blue") +
  geom_hline(yintercept=0, size = 1, linetype=3) +
  geom_ribbon(aes(ymin=lwr, ymax=upr), alpha=0.3) +
  theme_bw() +
  theme_bw(base_size = 12) +
  theme(axis.text.x = element_text(size=8),
           axis.text.y = element_text(size=8),
        axis.title=element_text(size=9)) +
  scale_y_continuous(limits = c(-.37, .3))

```

```{r}
s_rr <- d %>%
  subset(dem_leg ==1) %>%
  group_by(state_ab) %>%
  summarise(rr = mean(white_racial_resentment),
            black_pop = mean(s_p_black))
```

```{r fig.width=3.1, fig.height=2.7}
xhist  <- 
  axis_canvas(g2, axis = "x") + 
  geom_histogram(data = s_rr,
                 aes(x = rr),
                 color = 'black',
                 fill= 'lightgray') 

g2 <- g2 %>%
  insert_xaxis_grob(xhist , grid::unit(.3, "in"), position = "top") %>%
  ggdraw()

g2
```

### Figure 11.6

```{r }
beta.hat <- coef(m3)
vcov1 <- vcov(m3)
z0 <- seq(min(d$white_racial_resentment, na.rm = TRUE), max(d$white_racial_resentment, na.rm = TRUE), length.out = 1000)
dy.dx <- beta.hat["black_r"] + beta.hat["black_r:white_racial_resentment"]*z0
se.dy.dx <- sqrt(vcov1["black_r", "black_r"] + (z0^2)*vcov1["black_r:white_racial_resentment", "black_r:white_racial_resentment"] + 2*z0*vcov1["black_r", "black_r:white_racial_resentment"])
upr <- dy.dx + 1.96*se.dy.dx
lwr <- dy.dx - 1.96*se.dy.dx
g3 <- ggplot(data=NULL, aes(x=z0, y=dy.dx)) +
  labs(x="State White Racial Resentment (Scale: 1-5)", y="Marginal Effects",
       subtitle=paste("11.6 Republican Senators"),
       cex=4) +
  geom_line(aes(z0, dy.dx),size = 1) +
  geom_line(aes(z0, lwr), size = 1, linetype = 2, color="blue") +
  geom_line(aes(z0, upr), size = 1, linetype = 2, color="blue") +
  geom_hline(yintercept=0, size = 1, linetype=3) +
  geom_ribbon(aes(ymin=lwr, ymax=upr), alpha=0.3) +
  theme_bw() +
  theme_bw(base_size = 12) +
  theme(axis.text.x = element_text(size=8),
           axis.text.y = element_text(size=8),
        axis.title=element_text(size=9)) +
  scale_y_continuous(limits = c(-.37, .3))

```

```{r}
s_rr <- d %>%
  subset(dem_leg ==0) %>%
  group_by(state_ab) %>%
  summarise(rr = mean(white_racial_resentment),
            black_pop = mean(s_p_black))
```

```{r fig.width=3.1, fig.height=2.7}
xhist  <- 
  axis_canvas(g3, axis = "x") + 
  geom_histogram(data = s_rr,
                 aes(x = rr),
                 color = 'black',
                 fill= 'lightgray') 

g3 <- g3 %>%
  insert_xaxis_grob(xhist , grid::unit(.3, "in"), position = "top") %>%
  ggdraw()

g3
```

```{r}
grid.arrange(g1,g2,g3)
```

### Figure SI-P Senate

```{r message=FALSE, fig.width= 3.1, fig.height= 4}
g3_int <- interflex(Y = "outcome", D = "black_r", X = "s_p_black", data = as.data.frame(d), estimator = "binning", cutoffs = c(.1,.2,.3,.4,.5,.6),  vcov.type = "cluster", cl = "state.y", na.rm = T, main = "Marginal Effects of Being Black By Share\nof State Black on Dyadic Advantage\n(v. Whites) in the Senate", Ylabel = "Black-White Gap", Dlabel = "Black Respondent", Xlabel="Share of State Black",  theme.bw = TRUE, ylab = "Marginal Effect: Black Respondent", cex.main = .6, cex.lab = .7, cex.axis = .6, Z = c("latino_r", "asian_r" , "otherrace_r", "edu" , "income" , "female" , "age" , "ideo",  "pid7" , "log_s_vap" , "s_p_under35" , "s_p_over65" , "s_p_college" , "s_p_hs" , "s_medinc" , "s_p_black" , "s_p_api" , "s_p_latino" ), FE = c("year", "vote"), weights = "weight")

g3_int

g4_int <- interflex(Y = "outcome", D = "latino_r", X = "s_p_latino", data = as.data.frame(d),estimator = "binning", cutoffs = c(.1,.2,.3,.4,.5,.6,.7), na.rm = T, vcov.type = "cluster", cl = "state.y", main = "Marginal Effects of Being Latino By Share\nof State Latino on Dyadic Advantage\n(v. Whites) in the Senate", Ylabel = "Latino-White Gap", Dlabel = "Latino Respondent", Xlabel="Share of State Latino",   theme.bw = TRUE, ylab = "Marginal Effect: Latino Respondent", cex.main = .6, cex.lab = .7, cex.axis = .6, Z = c("black_r", "asian_r" , "otherrace_r", "edu" , "income" , "female" , "age" , "ideo",  "pid7" , "log_s_vap" , "s_p_under35" , "s_p_over65" , "s_p_college" , "s_p_hs" , "s_medinc" , "s_p_black" , "s_p_api" , "s_p_latino" ), FE = c("year", "vote"), weights = "weight")

g4_int

gc()
```

## SI-R

```{r}
d <- d %>%
  mutate(dem.presvote.lastup = ifelse(is.na(dem.presvote.lastup), 0, dem.presvote.lastup),
         close_election = ifelse(dem.presvote.lastup  <= .55 & dem.presvote.lastup >= .45, 1, 0) )
```

```{r}
m2 <- felm(outcome ~ black_r*s_p_black + latino_r*s_p_latino + asian_r*s_p_api + otherrace_r + edu + income + female + age + ideo + pid7 +
               log_s_vap + s_p_under35 + s_p_over65 + s_p_college + s_p_hs + s_medinc 
               | as.factor(year) + vote | 0 | state.y, data = subset(d, close_election == 1), weight = subset(d, close_election == 1)$weight)

m3 <- felm(outcome ~ black_r*s_p_black + latino_r*s_p_latino + asian_r*s_p_api + otherrace_r + edu + income + female + age + ideo + pid7 +
               log_s_vap + s_p_under35 + s_p_over65 + s_p_college + s_p_hs + s_medinc 
               | as.factor(year) + vote | 0 | state.y, data = subset(d, close_election == 0), weight = subset(d, close_election == 0)$weight)
```

```{r results='asis'}
stargazer(m2,m3,
          title = "Table SI-R",
          dep.var.labels.include = FALSE , 
          column.labels = c( "Competative States", "Non-Competative States"),
          column.sep.width = "1pt", 
          type = "html", 
          font.size = "small", 
          header=FALSE, 
          omit.stat = c("f", "ser"), 
          star.char = c("*", "**", "***"),
          star.cutoffs = c(.05, .01, .001),
          out = "Tables/Table SI-R.doc"
          )
```

### Figure SI-R

```{r}
beta.hat <- coef(m2)
vcov2 <- vcov(m2)
z02.s <- seq(min(d$s_p_black), max(d$s_p_black), length.out = 1000)
dy.dx2.s <- beta.hat["black_r"] + beta.hat["black_r:s_p_black"]*z02.s
se.dy.dx2.s <- sqrt(vcov2["black_r", "black_r"] + (z02.s^2)*vcov2["black_r:s_p_black", "black_r:s_p_black"] + 2*z02.s*vcov2["black_r", "black_r:s_p_black"])
upr2.s <- dy.dx2.s + 1.96*se.dy.dx2.s
lwr2.s <- dy.dx2.s - 1.96*se.dy.dx2.s
```

```{r}
beta.hat <- coef(m3)
vcov3 <- vcov(m3)
z03.s <- seq(min(d$s_p_black), max(d$s_p_black), length.out = 1000)
dy.dx3.s <- beta.hat["black_r"] + beta.hat["black_r:s_p_black"]*z03.s
se.dy.dx3.s <- sqrt(vcov3["black_r", "black_r"] + (z03.s^2)*vcov3["black_r:s_p_black", "black_r:s_p_black"] + 2*z03.s*vcov3["black_r", "black_r:s_p_black"])
upr3.s <- dy.dx3.s + 1.96*se.dy.dx3.s
lwr3.s <- dy.dx3.s - 1.96*se.dy.dx3.s
```

```{r}
g2.c <- ggplot(data=NULL, aes(x=z02.s, y=dy.dx2.s)) +
  labs(x="", y="",
       subtitle = "Black Respondent | Senate ",
       cex=4) +
  geom_line(aes(z02.s, dy.dx2.s),size = 1, color = "blue") +
  geom_line(aes(z02.s, lwr2.s), size = 1, linetype = 2, color="blue") +
  geom_line(aes(z02.s, upr2.s), size = 1, linetype = 2, color="blue") +
  geom_hline(yintercept=0, size = 1, linetype=3) +
  geom_ribbon(aes(ymin=lwr2.s, ymax=upr2.s), alpha=0.3, fill = "blue") +
  geom_line(aes(z03.s, dy.dx3.s),size = 1, color = "red") +
  geom_line(aes(z03.s, lwr3.s), size = 1, linetype = 2, color="red") +
  geom_line(aes(z03.s, upr3.s), size = 1, linetype = 2, color="red") +
  geom_hline(yintercept=0, size = 1, linetype=3) +
  geom_ribbon(aes(ymin=lwr3.s, ymax=upr3.s), alpha=0.3, fill = "red") +
  theme_bw() +
  theme(plot.subtitle = element_text(size = 12)) +
  scale_x_continuous(labels = percent) +
  scale_y_continuous(limits = c(-.37, .3)) +
  theme(plot.subtitle=element_text(size=10))
```

```{r}
beta.hat <- coef(m2)
vcov2.l <- vcov(m2)
z02.s.l <- seq(min(d$s_p_latino), max(d$s_p_latino), length.out = 1000)
dy.dx2.s.l <- beta.hat["latino_r"] + beta.hat["latino_r:s_p_latino"]*z02.s.l
se.dy.dx2.s.l <- sqrt(vcov2.l["latino_r", "latino_r"] + (z02.s.l^2)*vcov2.l["latino_r:s_p_latino", "latino_r:s_p_latino"] + 2*z02.s.l*vcov2.l["latino_r", "latino_r:s_p_latino"])
upr2.s.l <- dy.dx2.s.l + 1.96*se.dy.dx2.s.l
lwr2.s.l <- dy.dx2.s.l - 1.96*se.dy.dx2.s.l
```

```{r}
beta.hat <- coef(m3)
vcov3.l <- vcov(m3)
z03.s.l <- seq(min(d$s_p_latino), max(d$s_p_latino), length.out = 1000)
dy.dx3.s.l <- beta.hat["latino_r"] + beta.hat["latino_r:s_p_latino"]*z03.s.l
se.dy.dx3.s.l <- sqrt(vcov3.l["latino_r", "latino_r"] + (z03.s.l^2)*vcov3.l["latino_r:s_p_latino", "latino_r:s_p_latino"] + 2*z03.s.l*vcov3.l["latino_r", "latino_r:s_p_latino"])
upr3.s.l <- dy.dx3.s.l + 1.96*se.dy.dx3.s.l
lwr3.s.l <- dy.dx3.s.l - 1.96*se.dy.dx3.s.l
```

```{r}
g2.nc <- ggplot(data=NULL, aes(x=z02.s.l, y=dy.dx2.s.l)) +
  labs(x="", y="",
       subtitle = "Latino Respondent | Senate",
       cex=4) +
  geom_line(aes(z02.s.l, dy.dx2.s.l),size = 1, color = "blue") +
  geom_line(aes(z02.s.l, lwr2.s.l), size = 1, linetype = 2, color="blue") +
  geom_line(aes(z02.s.l, upr2.s.l), size = 1, linetype = 2, color="blue") +
  geom_hline(yintercept=0, size = 1, linetype=3) +
  geom_ribbon(aes(ymin=lwr2.s.l, ymax=upr2.s.l), alpha=0.3, fill = "blue") +
  geom_line(aes(z03.s.l, dy.dx3.s.l),size = 1, color = "red") +
  geom_line(aes(z03.s.l, lwr3.s.l), size = 1, linetype = 2, color="red") +
  geom_line(aes(z03.s.l, upr3.s.l), size = 1, linetype = 2, color="red") +
  geom_hline(yintercept=0, size = 1, linetype=3) +
  geom_ribbon(aes(ymin=lwr3.s.l, ymax=upr3.s.l), alpha=0.3, fill = "red") +
  theme_bw() +
  theme(plot.subtitle = element_text(size = 12)) +
  scale_x_continuous(labels = percent) +
  scale_y_continuous(limits = c(-.37,.3))+
  theme(plot.subtitle=element_text(size=10))
```


```{r}

legdata <- data.frame(c("Competitive", "Non-Competitive"), c(1,2,3,4), c(2,1,6,7))
colnames(legdata) <- c("Party", "X", "Y")

leg <- ggplot(data=legdata, aes(x=X, y=Y, color=Party, fill=Party)) +
  geom_line(size=4) +
  scale_color_manual(values = c("blue", "red")) +
  theme(legend.direction = "horizontal")

g_legend <- function(a.gplot){
  tmp <- ggplot_gtable(ggplot_build(a.gplot))
  leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
  legend <- tmp$grobs[[leg]]
  return(legend)
}

leg <- g_legend(leg)
```

```{r, fig.height=4, fig.width=6}

lay = rbind(c(1,1,1,1,2,2,2,2),
            c(1,1,1,1,2,2,2,2),
            c(1,1,1,1,2,2,2,2),
            c(1,1,1,1,2,2,2,2),
            c(1,1,1,1,2,2,2,2),
            c(1,1,1,1,2,2,2,2),
            c(1,1,1,1,2,2,2,2),
            c(NA,NA,3,3,3,3,NA,NA))

grid.arrange( g2.c, g2.nc, leg, layout_matrix=lay, 
             bottom = "Percent of State Population Black / Latino",
             left = "Marginal Effects")
```

## SI-S Senate

```{r}
#Race Simple Models with Controls
m2 <- felm(outcome ~ black_r*s_p_black + latino_r*s_p_latino + asian_r*s_p_api + otherrace_r + edu + income + female + age + ideo + pid7 +
               log_s_vap + s_p_under35 + s_p_over65 + s_p_college + s_p_hs + s_medinc 
               | as.factor(year) + vote | 0 | state.y, data = subset(d, southern_st == 1), weights = subset(d, southern_st == 1)$weight)

m3 <- felm(outcome ~ black_r*s_p_black + latino_r*s_p_latino + asian_r*s_p_api + otherrace_r + edu + income + female + age + ideo + pid7 +
               log_s_vap + s_p_under35 + s_p_over65 + s_p_college + s_p_hs + s_medinc 
               | as.factor(year) + vote | 0 | state.y, data = subset(d, southern_st == 0), weights = subset(d, southern_st == 0)$weight)
```

```{r results='asis'}
stargazer(m2,m3,
          title = "Table SI-S",
          dep.var.labels.include = FALSE , 
          column.labels = c("All MCs" , "Southern States", "Non-Southern States"),
          column.sep.width = "1pt", 
          type = "html", 
          font.size = "small", 
          header=FALSE, 
          omit.stat = c("f", "ser"), 
          star.char = c("*", "**", "***"),
          star.cutoffs = c(.05, .01, .001),
          out = "Tables/Table SI-S.doc"
          )
```

### Figure SI-S.3

```{r}
beta.hat <- coef(m3)
vcov2 <- vcov(m3)
z02.s <- seq(min(d$s_p_black), max(d$s_p_black), length.out = 1000)
dy.dx2.s <- beta.hat["black_r"] + beta.hat["black_r:s_p_black"]*z02.s
se.dy.dx2.s <- sqrt(vcov2["black_r", "black_r"] + (z02.s^2)*vcov2["black_r:s_p_black", "black_r:s_p_black"] + 2*z02.s*vcov2["black_r", "black_r:s_p_black"])
upr2.s <- dy.dx2.s + 1.96*se.dy.dx2.s
lwr2.s <- dy.dx2.s - 1.96*se.dy.dx2.s
```

```{r}
beta.hat <- coef(m2)
vcov3 <- vcov(m2)
z03.s <- seq(min(d$s_p_black), max(d$s_p_black), length.out = 1000)
dy.dx3.s <- beta.hat["black_r"] + beta.hat["black_r:s_p_black"]*z03.s
se.dy.dx3.s <- sqrt(vcov3["black_r", "black_r"] + (z03.s^2)*vcov3["black_r:s_p_black", "black_r:s_p_black"] + 2*z03.s*vcov3["black_r", "black_r:s_p_black"])
upr3.s <- dy.dx3.s + 1.96*se.dy.dx3.s
lwr3.s <- dy.dx3.s - 1.96*se.dy.dx3.s
```

```{r}
g2.sb <- ggplot(data=NULL, aes(x=z02.s, y=dy.dx2.s)) +
  labs(x="", y="",
       subtitle = "Black Respondent | Senate ",
       cex=4) +
  geom_line(aes(z02.s, dy.dx2.s),size = 1, color = "blue") +
  geom_line(aes(z02.s, lwr2.s), size = 1, linetype = 2, color="blue") +
  geom_line(aes(z02.s, upr2.s), size = 1, linetype = 2, color="blue") +
  geom_hline(yintercept=0, size = 1, linetype=3) +
  geom_ribbon(aes(ymin=lwr2.s, ymax=upr2.s), alpha=0.3, fill = "blue") +
  geom_line(aes(z03.s, dy.dx3.s),size = 1, color = "red") +
  geom_line(aes(z03.s, lwr3.s), size = 1, linetype = 2, color="red") +
  geom_line(aes(z03.s, upr3.s), size = 1, linetype = 2, color="red") +
  geom_hline(yintercept=0, size = 1, linetype=3) +
  geom_ribbon(aes(ymin=lwr3.s, ymax=upr3.s), alpha=0.3, fill = "red") +
  theme_bw() +
  theme(plot.subtitle = element_text(size = 12)) +
  scale_x_continuous(labels = percent) +
  scale_y_continuous(limits = c(-.37, .3)) +
  theme(plot.subtitle=element_text(size=10))
```

### Figure SI-S.4

```{r}
beta.hat <- coef(m3)
vcov2.l <- vcov(m3)
z02.s.l <- seq(min(d$s_p_latino), max(d$s_p_latino), length.out = 1000)
dy.dx2.s.l <- beta.hat["latino_r"] + beta.hat["latino_r:s_p_latino"]*z02.s.l
se.dy.dx2.s.l <- sqrt(vcov2.l["latino_r", "latino_r"] + (z02.s.l^2)*vcov2.l["latino_r:s_p_latino", "latino_r:s_p_latino"] + 2*z02.s.l*vcov2.l["latino_r", "latino_r:s_p_latino"])
upr2.s.l <- dy.dx2.s.l + 1.96*se.dy.dx2.s.l
lwr2.s.l <- dy.dx2.s.l - 1.96*se.dy.dx2.s.l
```

```{r}
beta.hat <- coef(m2)
vcov3.l <- vcov(m2)
z03.s.l <- seq(min(d$s_p_latino), max(d$s_p_latino), length.out = 1000)
dy.dx3.s.l <- beta.hat["latino_r"] + beta.hat["latino_r:s_p_latino"]*z03.s.l
se.dy.dx3.s.l <- sqrt(vcov3.l["latino_r", "latino_r"] + (z03.s.l^2)*vcov3.l["latino_r:s_p_latino", "latino_r:s_p_latino"] + 2*z03.s.l*vcov3.l["latino_r", "latino_r:s_p_latino"])
upr3.s.l <- dy.dx3.s.l + 1.96*se.dy.dx3.s.l
lwr3.s.l <- dy.dx3.s.l - 1.96*se.dy.dx3.s.l
```

```{r}
g2.sl <- ggplot(data=NULL, aes(x=z02.s.l, y=dy.dx2.s.l)) +
  labs(x="", y="",
       subtitle = "Latino Respondent | Senate",
       cex=4) +
  geom_line(aes(z02.s.l, dy.dx2.s.l),size = 1, color = "blue") +
  geom_line(aes(z02.s.l, lwr2.s.l), size = 1, linetype = 2, color="blue") +
  geom_line(aes(z02.s.l, upr2.s.l), size = 1, linetype = 2, color="blue") +
  geom_hline(yintercept=0, size = 1, linetype=3) +
  geom_ribbon(aes(ymin=lwr2.s.l, ymax=upr2.s.l), alpha=0.3, fill = "blue") +
  geom_line(aes(z03.s.l, dy.dx3.s.l),size = 1, color = "red") +
  geom_line(aes(z03.s.l, lwr3.s.l), size = 1, linetype = 2, color="red") +
  geom_line(aes(z03.s.l, upr3.s.l), size = 1, linetype = 2, color="red") +
  geom_hline(yintercept=0, size = 1, linetype=3) +
  geom_ribbon(aes(ymin=lwr3.s.l, ymax=upr3.s.l), alpha=0.3, fill = "red") +
  theme_bw() +
  theme(plot.subtitle = element_text(size = 12)) +
  scale_x_continuous(labels = percent) +
  scale_y_continuous(limits = c(-.37,.3))+
  theme(plot.subtitle=element_text(size=10))
```

### Figure SI-S

```{r}
legdata <- data.frame(c("South", "Non-South", "South", "Non-South"), c(1,2,3,4), c(2,1,6,7))
colnames(legdata) <- c("Party", "X", "Y")

leg <- ggplot(data=legdata, aes(x=X, y=Y, color=Party, fill=Party)) +
  geom_line(size=4) +
  scale_color_manual(values = c("blue", "red")) +
  theme(legend.direction = "horizontal")

g_legend <- function(a.gplot){
  tmp <- ggplot_gtable(ggplot_build(a.gplot))
  leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
  legend <- tmp$grobs[[leg]]
  return(legend)
}

leg <- g_legend(leg)
```

```{r, fig.height=6, fig.width=6}
lay = rbind(c(1,1,1,1,2,2,2,2),
            c(1,1,1,1,2,2,2,2),
            c(1,1,1,1,2,2,2,2),
            c(1,1,1,1,2,2,2,2),
            c(1,1,1,1,2,2,2,2),
            c(1,1,1,1,2,2,2,2),
            c(1,1,1,1,2,2,2,2),
            c(3,3,3,3,4,4,4,4),
            c(3,3,3,3,4,4,4,4),
            c(3,3,3,3,4,4,4,4),
            c(3,3,3,3,4,4,4,4),
            c(3,3,3,3,4,4,4,4),
            c(3,3,3,3,4,4,4,4),
            c(3,3,3,3,4,4,4,4),
            c(NA,NA,5,5,5,5,NA,NA))

grid.arrange( g2b.sou, g2l.sou, g2.sb, g2.sl, leg, layout_matrix=lay, 
             bottom = "Percent of the District / State Population Black / Latino",
             left = "Marginal Effects")
```

## SI-T

### Figure SI-T1

```{r}
s_rr <- d %>%
  group_by(state_ab) %>%
  summarise(rr = mean(white_racial_resentment),
            black_pop = mean(s_p_black),
            latino_pop = mean(s_p_latino))
```

```{r}
ggplot(s_rr, aes(x = black_pop, y = rr, label=state_ab)) +
  geom_text(check_overlap = TRUE, size = 3, position = "jitter") +
  geom_smooth(method = "lm", alpha = .2) +
  labs(x = "Black Share of State Population", y = "Mean Racial Resentment Score of White Residents") +
  theme_bw() +
  scale_x_continuous(labels = percent)
```

### Figure SI-T2

```{r}
ggplot(s_rr, aes(x = latino_pop, y = rr, label=state_ab)) +
  geom_text(check_overlap = TRUE, size = 3, position = "jitter") +
  geom_smooth(method = "lm", alpha = .2) +
  labs(x = "Latino Share of State Population", y = "Mean Racial Resentment Score of White Residents") +
  theme_bw() +
  scale_x_continuous(labels = percent)
```

### Table SI-T

```{r}
#Race Simple Models with Controls
m1 <- felm(outcome ~ black_r*s_p_black + latino_r*s_p_latino + asian_r*s_p_api + black_r*white_racial_resentment + latino_r*white_racial_resentment + otherrace_r + edu + income + female + ideo + pid7 + age +
               log_s_vap + s_p_under35 + s_p_over65 + s_p_college + s_p_hs + s_medinc 
               | as.factor(year) + vote | 0 | state.y, data = d)
```

```{r results='asis'}
stargazer(m1,
          title = "Table SI-T",
          dep.var.labels.include = FALSE , 
          column.labels = c("All MCs" , "Democratic MCs", "Republican MCs"),
          column.sep.width = "1pt", 
          type = "html", 
          font.size = "small", 
          header=FALSE, 
          omit.stat = c("f", "ser"), 
          star.char = c("*", "**", "***"),
          star.cutoffs = c(.05, .01, .001),
          out = "Tables/Table SI-T.doc"
          )
```

### SI-V Inputs Senate

```{r}
m2 <- felm(outcome ~ black_r*white_racial_resentment + latino_r + asian_r + otherrace_r + edu + income + female + age + ideo + pid7 +
               log_s_vap + s_p_under35 + s_p_over65 + s_p_college + s_p_hs + s_medinc + s_p_black + s_p_api + s_p_latino
               | as.factor(year) + vote | 0 | state.y, data = subset(d, southern_st==1), weights = subset(d, southern_st==1)$weight)

m3 <- felm(outcome ~ black_r*white_racial_resentment + latino_r + asian_r + otherrace_r + edu + income + female + age + ideo + pid7 +
               log_s_vap + s_p_under35 + s_p_over65 + s_p_college + s_p_hs + s_medinc + s_p_black + s_p_api + s_p_latino
               | as.factor(year) + vote | 0 | state.y, data = subset(d, southern_st==0), weights = subset(d, southern_st==0)$weight)
```

```{r results='asis'}
stargazer(m2,m3,
          title = "Figure SI-V.3-4",
          dep.var.labels.include = FALSE , 
          column.sep.width = "1pt", 
          type = "html",
          font.size = "small", 
          header=FALSE, 
          omit.stat = c("f", "ser"), 
          star.char = c("*", "**", "***"),
          star.cutoffs = c(.05, .01, .001)
          )
```

### Figure SI-V

```{r }
beta.hat <- coef(m2)
vcov1 <- vcov(m2)
z0 <- seq(min(d$white_racial_resentment, na.rm = TRUE), max(d$white_racial_resentment, na.rm = TRUE), length.out = 1000)
dy.dx <- beta.hat["black_r"] + beta.hat["black_r:white_racial_resentment"]*z0
se.dy.dx <- sqrt(vcov1["black_r", "black_r"] + (z0^2)*vcov1["black_r:white_racial_resentment", "black_r:white_racial_resentment"] + 2*z0*vcov1["black_r", "black_r:white_racial_resentment"])
upr <- dy.dx + 1.96*se.dy.dx
lwr <- dy.dx - 1.96*se.dy.dx

g2 <- ggplot(data=NULL, aes(x=z0, y=dy.dx)) +
  labs(x="State White Racial Resentment (Scale: 1-5)", y="Marginal Effects",
       subtitle=paste("Southern Senators"),
       cex=4) +
  geom_line(aes(z0, dy.dx),size = 1) +
  geom_line(aes(z0, lwr), size = 1, linetype = 2, color="blue") +
  geom_line(aes(z0, upr), size = 1, linetype = 2, color="blue") +
  geom_hline(yintercept=0, size = 1, linetype=3) +
  geom_ribbon(aes(ymin=lwr, ymax=upr), alpha=0.3) +
  theme_bw() +
  theme_bw(base_size = 12) +
  theme(axis.text.x = element_text(size=8),
           axis.text.y = element_text(size=8),
        axis.title=element_text(size=9)) +
  scale_y_continuous(limits = c(-.37, .35))

```

```{r}
s_rr <- d %>%
  subset(southern_st ==1) %>%
  group_by(state_ab) %>%
  summarise(rr = mean(white_racial_resentment),
            black_pop = mean(s_p_black))
```

```{r fig.width=3.1, fig.height=2.7}
xhist  <- 
  axis_canvas(g2, axis = "x") + 
  geom_histogram(data = s_rr,
                 aes(x = rr),
                 color = 'black',
                 fill= 'lightgray') 

g2 <- g2 %>%
  insert_xaxis_grob(xhist , grid::unit(.3, "in"), position = "top") %>%
  ggdraw()

g2
```

```{r }
beta.hat <- coef(m3)
vcov1 <- vcov(m3)
z0 <- seq(min(d$white_racial_resentment, na.rm = TRUE), max(d$white_racial_resentment, na.rm = TRUE), length.out = 1000)
dy.dx <- beta.hat["black_r"] + beta.hat["black_r:white_racial_resentment"]*z0
se.dy.dx <- sqrt(vcov1["black_r", "black_r"] + (z0^2)*vcov1["black_r:white_racial_resentment", "black_r:white_racial_resentment"] + 2*z0*vcov1["black_r", "black_r:white_racial_resentment"])
upr <- dy.dx + 1.96*se.dy.dx
lwr <- dy.dx - 1.96*se.dy.dx
g3 <- ggplot(data=NULL, aes(x=z0, y=dy.dx)) +
  labs(x="State White Racial Resentment (Scale: 1-5)", y="Marginal Effects",
       subtitle=paste("Non-Southern Senators"),
       cex=4) +
  geom_line(aes(z0, dy.dx),size = 1) +
  geom_line(aes(z0, lwr), size = 1, linetype = 2, color="blue") +
  geom_line(aes(z0, upr), size = 1, linetype = 2, color="blue") +
  geom_hline(yintercept=0, size = 1, linetype=3) +
  geom_ribbon(aes(ymin=lwr, ymax=upr), alpha=0.3) +
  theme_bw() +
  theme_bw(base_size = 12) +
  theme(axis.text.x = element_text(size=8),
           axis.text.y = element_text(size=8),
        axis.title=element_text(size=9)) +
  scale_y_continuous(limits = c(-.37, .35))

```

```{r}
s_rr <- d %>%
  subset(southern_st ==0) %>%
  group_by(state_ab) %>%
  summarise(rr = mean(white_racial_resentment),
            black_pop = mean(s_p_black))
```

```{r fig.width=3.1, fig.height=2.7}
xhist  <- 
  axis_canvas(g3, axis = "x") + 
  geom_histogram(data = s_rr,
                 aes(x = rr),
                 color = 'black',
                 fill= 'lightgray') 

g3 <- g3 %>%
  insert_xaxis_grob(xhist , grid::unit(.3, "in"), position = "top") %>%
  ggdraw()

g3
```

### Table SI-V

```{r}
#Race Simple Models with Controls
m1 <- felm(outcome ~ black_r*mrp_ideology + black_r*white_racial_resentment + latino_r + asian_r + otherrace_r + edu + income + female + age + ideo + pid7 + log_s_vap + s_p_under35 + s_p_over65 + s_p_college + s_p_hs + s_medinc + s_p_black + s_p_api + s_p_latino
               | as.factor(year) + vote | 0 | state.y, data = d, weights = d$weight)

m2 <- felm(outcome ~ black_r*mrp_ideology + black_r*white_racial_resentment + latino_r + asian_r  + otherrace_r + edu + income + female + age + ideo + pid7 + log_s_vap + s_p_under35 + s_p_over65 + s_p_college + s_p_hs + s_medinc + s_p_black + s_p_api + s_p_latino
               | as.factor(year) + vote | 0 | state.y, data = subset(d, dem_leg == 1), weights = subset(d, dem_leg == 1)$weight)

m3 <- felm(outcome ~ black_r*mrp_ideology + black_r*white_racial_resentment + latino_r + asian_r  + otherrace_r + edu + income + female + age + ideo + pid7 + log_s_vap + s_p_under35 + s_p_over65 + s_p_college + s_p_hs + s_medinc + s_p_black + s_p_api + s_p_latino
               | as.factor(year) + vote | 0 | state.y, data = subset(d, dem_leg == 0), weights = subset(d, dem_leg == 0)$weight)
```

```{r results='asis'}
stargazer(m1,m2,m3,
          title = "Table SI-V",
  
          dep.var.labels.include = FALSE , 
          column.labels = c("All MCs" , "Democratic MCs", "Republican MCs"),
          column.sep.width = "1pt", 
          type = "html", 
          font.size = "small", 
          header=FALSE, 
          omit.stat = c("f", "ser"), 
          star.char = c("*", "**", "***"),
          star.cutoffs = c(.05, .01, .001),
          out = "Tables/Table SI-V.doc"
          )
```




